package com.ybkj.daijia.server.service.impl;

import com.ybkj.daijia.serverUtils.HttpClientUtil;
import com.ybkj.daijia.InfoFeeType;
import com.ybkj.daijia.OrderNumberConfig;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.serverUtils.UseAllDataUtil;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.common.Distance;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.common.SquareLocation;
import com.ybkj.daijia.config.PassengerApi;
import com.ybkj.daijia.config.SalesApi;
import com.ybkj.daijia.config.ZWYApi;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.OrderRevokeTimerTask;
import com.ybkj.daijia.server.OrderTimerTask;
import com.ybkj.daijia.server.errand.SelectPrice;
import com.ybkj.daijia.server.event.model.DjxNoticeEvent;
import com.ybkj.daijia.server.event.model.MemberConsumedEvent;
import com.ybkj.daijia.server.event.model.OrderArriveFromPlaceEvent;
import com.ybkj.daijia.server.event.model.OrderCancelEvent;
import com.ybkj.daijia.server.event.model.OrderCancelYupaiEvent;
import com.ybkj.daijia.server.event.model.OrderCreateEvent;
import com.ybkj.daijia.server.event.model.OrderInputHistoryEvent;
import com.ybkj.daijia.server.event.model.OrderPaidanEvent;
import com.ybkj.daijia.server.event.model.OrderPowerCancelEvent;
import com.ybkj.daijia.server.event.model.OrderPowerRevokeEvent;
import com.ybkj.daijia.server.event.model.OrderQingqiujieEvent;
import com.ybkj.daijia.server.event.model.OrderRecordEvent;
import com.ybkj.daijia.server.event.model.OrderRefuseEvent;
import com.ybkj.daijia.server.event.model.OrderRevokeEvent;
import com.ybkj.daijia.server.event.model.OrderRevokelYupaiEvent;
import com.ybkj.daijia.server.event.model.OrderRushEvent;
import com.ybkj.daijia.server.event.model.OrderStartDriveEvent;
import com.ybkj.daijia.server.event.model.OrderZhuandanEvent;
import com.ybkj.daijia.server.event.model.YwxNoticeEvent;
import com.ybkj.daijia.server.mapper.AreaMapper;
import com.ybkj.daijia.server.mapper.AreaOfEmployMapper;
import com.ybkj.daijia.server.mapper.ChartDayMapper;
import com.ybkj.daijia.server.mapper.ChartMonthMapper;
import com.ybkj.daijia.server.mapper.CompanyMapper;
import com.ybkj.daijia.server.mapper.DjInsuranceMapper;
import com.ybkj.daijia.server.mapper.DriverChoseLevelCarMapper;
import com.ybkj.daijia.server.mapper.DriverChoseLevelMapper;
import com.ybkj.daijia.server.mapper.DriverLevelDetailMapper;
import com.ybkj.daijia.server.mapper.DriverLevelMapper;
import com.ybkj.daijia.server.mapper.DriverLevelMoneyTimeDetailMapper;
import com.ybkj.daijia.server.mapper.DriverMapper;
import com.ybkj.daijia.server.mapper.DriverPaymentsRecordMapper;
import com.ybkj.daijia.server.mapper.DriverRefuseRecordMapper;
import com.ybkj.daijia.server.mapper.FinancialRecordMapper;
import com.ybkj.daijia.server.mapper.FirstOrderPassengerMapper;
import com.ybkj.daijia.server.mapper.InsuranceMapper;
import com.ybkj.daijia.server.mapper.OperationLogMapper;
import com.ybkj.daijia.server.mapper.OrderFinishedInfoMapper;
import com.ybkj.daijia.server.mapper.OrderGroupMapper;
import com.ybkj.daijia.server.mapper.OrderMapper;
import com.ybkj.daijia.server.mapper.OrderOrbitMapper;
import com.ybkj.daijia.server.mapper.OrderRefuseRecordMapper;
import com.ybkj.daijia.server.mapper.OrderStatusMapper;
import com.ybkj.daijia.server.mapper.PhoneSmsRecordMapper;
import com.ybkj.daijia.server.mapper.RateMapper;
import com.ybkj.daijia.server.mapper.ReimbursementMapper;
import com.ybkj.daijia.server.mapper.SmsTempletMapper;
import com.ybkj.daijia.server.mapper.UsuallyDriverMapper;
import com.ybkj.daijia.server.mapper.WeixinManagerMapper;
import com.ybkj.daijia.server.mapper.WeixinManagerPaymentsMapper;
import com.ybkj.daijia.server.mapper.WeixinManagerXOrderMapper;
import com.ybkj.daijia.server.mc.Enterprise;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.mc.PassengerAccount;
import com.ybkj.daijia.server.mc.PassengerAddress;
import com.ybkj.daijia.server.mc.PassengerGrade;
import com.ybkj.daijia.server.model.Area;
import com.ybkj.daijia.server.model.AreaOfEmploy;
import com.ybkj.daijia.server.model.ChargeStartDistance;
import com.ybkj.daijia.server.model.ChargeStartTime;
import com.ybkj.daijia.server.model.ChargeStartTimeOfEmploy;
import com.ybkj.daijia.server.model.ChartDay;
import com.ybkj.daijia.server.model.ChartMonth;
import com.ybkj.daijia.server.model.ChartYear;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.DjInsurance;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverChoseLevel;
import com.ybkj.daijia.server.model.DriverChoseLevelCar;
import com.ybkj.daijia.server.model.DriverLevel;
import com.ybkj.daijia.server.model.DriverLevel.TimePoint;
import com.ybkj.daijia.server.model.DriverLevelDetail;
import com.ybkj.daijia.server.model.DriverLevelDetail.DriverLevelType;
import com.ybkj.daijia.server.model.DriverLevelMoneyDetail;
import com.ybkj.daijia.server.model.DriverLevelMoneyDetail.DriverLevelMoneyType;
import com.ybkj.daijia.server.model.DriverLevelMoneyTimeDetail;
import com.ybkj.daijia.server.model.DriverPaymentsRecord;
import com.ybkj.daijia.server.model.DriverRefuseRecord;
import com.ybkj.daijia.server.model.FinancialRecord;
import com.ybkj.daijia.server.model.FirstOrderPassenger;
import com.ybkj.daijia.server.model.Insurance;
import com.ybkj.daijia.server.model.OperationLog;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.Order.PayType;
import com.ybkj.daijia.server.model.Order.PayTypeDetails;
import com.ybkj.daijia.server.model.OrderFinishedInfo;
import com.ybkj.daijia.server.model.OrderGroup;
import com.ybkj.daijia.server.model.OrderOrbit;
import com.ybkj.daijia.server.model.OrderRefuseRecord;
import com.ybkj.daijia.server.model.OrderStatus;
import com.ybkj.daijia.server.model.OrderStatus.StatusType;
import com.ybkj.daijia.server.model.Rate;
import com.ybkj.daijia.server.model.Reimbursement;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.model.UsuallyDriver;
import com.ybkj.daijia.server.model.WeixinManager;
import com.ybkj.daijia.server.model.WeixinManager.WeixinManagerMoneyType;
import com.ybkj.daijia.server.model.WeixinManagerPayments;
import com.ybkj.daijia.server.model.WeixinManagerXOrder;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Coupon;
import com.ybkj.daijia.server.sales.CouponRule;
import com.ybkj.daijia.server.scheduler.ThreadControl;
import com.ybkj.daijia.server.service.ChartYearService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.OrderStatusService;
import com.ybkj.daijia.server.service.SmsService;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;

/**
 * @author Shine
 */
@Service
public class DefaultOrderService implements OrderService {

    private static final Logger logger = LoggerFactory.getLogger(DefaultOrderService.class);

    @Autowired
    private OrderStatusService orderStatusService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RateMapper rateMapper;

    @Autowired
    private OrderGroupMapper orderGroupMapper;

    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private AreaOfEmployMapper areaOfEmployMapper;

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private DriverMapper driverMapper;

    @Autowired
    private MemberService memberService;

    @Autowired
    private DriverLevelMapper driverLevelMapper;

    @Autowired
    private DriverChoseLevelMapper driverChoseLevelMapper;

    @Autowired
    private DriverChoseLevelCarMapper driverChoseLevelCarMapper;

    @Autowired
    private DriverLevelDetailMapper driverLevelDetailMapper;

    @Autowired
    private DriverLevelMoneyTimeDetailMapper driverLevelMoneyTimeDetailMapper;

    @Autowired
    private OrderStatusMapper orderStatusMapper;

    @Autowired
    private FinancialRecordMapper financialRecordMapper;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private OrderOrbitMapper orderOrbitMapper;

    @Autowired
    private ReimbursementMapper reimbursementMapper;

    // @Autowired
    // private WorkCarPickupService workCarPickupService;

    @Autowired
    private WeixinManagerXOrderMapper weixinManagerXOrderMapper;

    @Autowired
    private WeixinManagerMapper weixinManagerMapper;

    @Autowired
    private UsuallyDriverMapper usuallyDriverMapper;

    @Autowired
    private SmsTempletMapper smsTempletMapper;

    @Autowired
    private ChartYearService chartYearService;

    @Autowired
    private ChartMonthMapper chartMonthMapper;

    @Autowired
    private ChartDayMapper chartDayMapper;

    @Autowired
    private OperationLogMapper operationLogMapper;

    @Autowired
    private OrderRefuseRecordMapper orderRefuseRecordMapper;

    @Autowired
    private OrderFinishedInfoMapper orderFinishedInfoMapper;

    @Autowired
    private InsuranceMapper insuranceMapper;

    @Autowired
    private TaskExecutor taskExecutor;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private PhoneSmsRecordMapper phoneSmsRecordMapper;

    @Autowired
    private DriverRefuseRecordMapper driverRefuseRecordMapper;

    @Autowired
    private PassengerApi passengerApi;

    @Autowired
    private SalesApi salesApi;

    @Autowired
    private FirstOrderPassengerMapper firstOrderPassengerMapper;

    @Autowired
    private DriverPaymentsRecordMapper driverPaymentsRecordMapper;

    @Autowired
    private DjInsuranceMapper djInsuranceMapper;

    @Autowired
    private WeixinManagerPaymentsMapper weixinManagerPaymentsMapper;

    @Autowired
    private SmsService smsService;

    @Autowired
    private ZWYApi zWYApi;

    @Override
    public List<Order> findAllFinished(Integer page, Integer limit) {
        return orderMapper.selectAllFinished(page * limit, limit);
    }

    @Override
    public Long countAllFinished() {

        return orderMapper.countAllFinished();
    }

    /*
     * (non-Javadoc)
     *
     * @see com.ybkj.shop.service.AdminService#queryAll()
     */
    public Page<Order> queryAll(final String param) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        String likeParam = null;
        if (StringUtils.isNotBlank(param)) {
            likeParam = "%" + param + "%";
        }

        List<Order> content = new ArrayList<Order>();
        long total = 0;

        if (!principal.isCompanyType()) {
            content = orderMapper.selectAllByCompanyWithParams(principal.getCompanyId(), likeParam,
                Pager.getOffset(),
                Pager.getLimit());
            total = orderMapper.countAllByCompanyWithParams(principal.getCompanyId(), likeParam);
        } else {
            content = orderMapper
                .selectAllByCompanyWithParams(null, likeParam, Pager.getOffset(), Pager.getLimit());
            total = orderMapper.countAllByCompanyWithParams(null, likeParam);
        }

        if (total > 0) {
            for (Order order : content) {
                order.setCompany(companyMapper.selectByPrimaryKey(order.getCompanyId()));
                order.setInsurance(insuranceMapper.selectByOrderId(order.getId()));
            }
        }

        return new PageImpl<Order>(content, pageable, total);

    }

    @Override
    public Page<OrderStatus> queryRefuse(String param) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        String likeParam = null;
        if (StringUtils.isNotBlank(param)) {
            likeParam = "%" + param + "%";
        }

        List<OrderStatus> content = new ArrayList<OrderStatus>();
        long total = 0;

        if (!principal.isCompanyType()) {
            content = orderStatusMapper.selectByCompanyAndTypeWithParams(principal.getCompanyId(),
                OrderStatus.StatusType.refuse, likeParam, Pager.getOffset(), Pager.getLimit());
            total = orderStatusMapper.countByCompanyAndTypeWithParams(principal.getCompanyId(),
                OrderStatus.StatusType.refuse, likeParam);
        } else {
            content = orderStatusMapper
                .selectByCompanyAndTypeWithParams(null, OrderStatus.StatusType.refuse, likeParam,
                    Pager.getOffset(), Pager.getLimit());
            total = orderStatusMapper
                .countByCompanyAndTypeWithParams(null, OrderStatus.StatusType.refuse, likeParam);
        }

        if (total > 0) {
            for (OrderStatus orderStatus : content) {
                orderStatus.setOrder(orderMapper.selectByPrimaryKey(orderStatus.getOrderId()));
            }
        }

        return new PageImpl<OrderStatus>(content, pageable, total);

    }

    @Override
    public Page<Order> queryCancel(final String param) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        String likeParam = null;
        if (StringUtils.isNotBlank(param)) {
            likeParam = "%" + param + "%";

        }

        List<Order> content = new ArrayList<Order>();
        long total = 0;

        if (!principal.isCompanyType()) {
            content = orderMapper
                .selectCancelByCompanyWithParams(principal.getCompanyId(), likeParam,
                    Pager.getOffset(), Pager.getLimit());
            total = orderMapper.countCancelByCompanyWithParams(principal.getCompanyId(), likeParam);
        } else {
            content = orderMapper
                .selectCancelByCompanyWithParams(null, likeParam, Pager.getOffset(),
                    Pager.getLimit());
            total = orderMapper.countCancelByCompanyWithParams(null, likeParam);
        }

        if (total > 0) {
            for (Order order : content) {
                order.setCompany(companyMapper.selectByPrimaryKey(order.getCompanyId()));
                order.setOrderStatuss(orderStatusMapper.selectByOrder(order.getId()));
            }
        }

        return new PageImpl<Order>(content, pageable, total);

    }

    @Override
    public Page<Order> queryWarm(final String param) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        String likeParam = null;
        if (StringUtils.isNotBlank(param)) {
            likeParam = "%" + param + "%";
        }

        List<Order> content = new ArrayList<Order>();
        long total = 0;

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -2);
        Date date = calendar.getTime();

        if (!principal.isCompanyType()) {
            content = orderMapper
                .selectWarmByCompanyWithParams(principal.getCompanyId(), likeParam, date,
                    Pager.getOffset(), Pager.getLimit());
            total = orderMapper
                .countWarmByCompanyWithParams(principal.getCompanyId(), likeParam, date);
        } else {
            content = orderMapper
                .selectWarmByCompanyWithParams(null, likeParam, date, Pager.getOffset(),
                    Pager.getLimit());
            total = orderMapper.countWarmByCompanyWithParams(null, likeParam, date);
        }

        if (total > 0) {
            for (Order order : content) {
                order.setCompany(companyMapper.selectByPrimaryKey(order.getCompanyId()));
                order.setOrderStatuss(orderStatusMapper.selectByOrder(order.getId()));
            }
        }

        return new PageImpl<Order>(content, pageable, total);

    }

    @Override
    public Page<Order> queryFinish(String param, String payType) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        String likeParam = null;
        String equalPayType = null;
        if (StringUtils.isNotBlank(param)) {
            likeParam = "%" + param + "%";
        }
        if (StringUtils.isNotBlank(payType)) {
            equalPayType = payType;
        }

        List<Order> content = new ArrayList<Order>();
        long total = 0;

        if (!principal.isCompanyType()) {
            content = orderMapper
                .selectFinishedByCompanyWithParams(principal.getCompanyId(), likeParam,
                    equalPayType,
                    Pager.getOffset(), Pager.getLimit());
            total = orderMapper
                .countFinishedByCompanyWithParams(principal.getCompanyId(), likeParam,
                    equalPayType);
        } else {
            content = orderMapper
                .selectFinishedByCompanyWithParams(null, likeParam, equalPayType, Pager.getOffset(),
                    Pager.getLimit());
            total = orderMapper.countFinishedByCompanyWithParams(null, likeParam, equalPayType);
        }

        if (total > 0) {
            for (Order order : content) {
                order.setCompany(companyMapper.selectByPrimaryKey(order.getCompanyId()));
                order.setOrderStatuss(orderStatusMapper.selectByOrder(order.getId()));
                order.setInsurance(insuranceMapper.selectByOrderId(order.getId()));
            }
        }

        return new PageImpl<Order>(content, pageable, total);
    }

    @Override
    public Page<Order> queryBaodan(String param, String payType) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        String likeParam = null;
        String equalPayType = null;
        if (StringUtils.isNotBlank(param)) {
            likeParam = "%" + param + "%";
        }

        if (StringUtils.isNotBlank(payType)) {
            equalPayType = payType;
        }
        List<Order> content = new ArrayList<Order>();
        long total = 0;

        if (!principal.isCompanyType()) {
            content = orderMapper
                .selectBaodanByCompanyWithParams(principal.getCompanyId(), likeParam, equalPayType,
                    Pager.getOffset(), Pager.getLimit());
            total = orderMapper
                .countBaodanByCompanyWithParams(principal.getCompanyId(), likeParam, equalPayType);
        } else {
            content = orderMapper
                .selectBaodanByCompanyWithParams(null, likeParam, equalPayType, Pager.getOffset(),
                    Pager.getLimit());
            total = orderMapper.countBaodanByCompanyWithParams(null, likeParam, equalPayType);
        }

        if (total > 0) {
            for (Order order : content) {
                order.setCompany(companyMapper.selectByPrimaryKey(order.getCompanyId()));
                order.setOrderStatuss(orderStatusMapper.selectByOrder(order.getId()));
                order.setInsurance(insuranceMapper.selectByOrderId(order.getId()));
            }
        }

        return new PageImpl<Order>(content, pageable, total);
    }

    @Transactional(rollbackFor = Exception.class)
    public Order update(Order order) {

        orderMapper.updateByPrimaryKey(order);

        return order;

    }

    public Order findOne(Long id) {

        return orderMapper.selectByPrimaryKey(id);
    }

    public List<Order> findByIdIn(Long[] ids) {

        return orderMapper.selectByIdIn(ids);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(Order order) {

        orderMapper.deleteByPrimaryKey(order.getId());

    }

    @Transactional(rollbackFor = Exception.class)
    public List<Order> createAndPaidan(Order order, Integer driverNum, Long[] couponIds,
        Double longitude,
        Double latitude, Long[] check_drivers, Long companyId, Long weixinManagerId,
        BigDecimal fixPriceMoney,
        BigDecimal yuguMoney) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Company company = companyMapper.selectByPrimaryKey(companyId);

        // 根据客户电话查询客户
        Result<Passenger> result_p = passengerApi
            .findOnePassengerByPhone(order.getClientPhone(), settingUtils.get());
        Passenger passenger = result_p.getResult();
        if (null != passenger) {
            // 老客户 更新位置
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            if (!StringUtils.isBlank(order.getClientName()) && StringUtils
                .isBlank(passenger.getName())) {
                passenger.setName(order.getClientName());
                passengerApi.updatePersonal(passenger, settingUtils.get());
            }
        } else {
            // 新客户
            passenger = new Passenger();
            passenger.setName(order.getClientName());
            passenger.setPhone(order.getClientPhone());
            passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_PHONE);
            passenger.setType(Passenger.TYPE_PASSENGER);
            passenger.setAllowOverdraw(false);
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            passenger.setCompanyId(company.getId());
            passenger.setCompanyName(company.getAbbreviation());

            Result<Passenger> result = passengerApi.createPersonal(passenger, settingUtils.get());
            passenger = result.getResult();
        }

        DateFormat format = new SimpleDateFormat("yyyyMMdd");

        List<Driver> drivers = driverMapper.selectByIdIn(check_drivers);

        order.setCompanyId(company.getId());
        order.setDjxFee(company.getDjxFee());
        order.setYwxFee(company.getYwxFee());
        order.setManagerId(weixinManagerId);

        if (order.isFixPrice()) {
            order.setShouldCash(fixPriceMoney);
        } else {
            order.setShouldCash(yuguMoney);
        }

        order.setClientLongitude(longitude);
        order.setClientLatitude(latitude);
        order.setClientId(passenger.getId());

        if (passenger.isInBlackList()) {
            order.setMemo("黑名单客户");
        }

        if (driverNum > 1) {
            OrderGroup orderGroup = new OrderGroup();
            orderGroupMapper.insertRecord(orderGroup);
            order.setOrderGroupId(orderGroup.getId());
            if (StringUtils.isBlank(order.getMemo())) {
                order.setMemo("客户同时预约" + driverNum + "人");
            } else {
                order.setMemo(order.getMemo() + ";" + "客户同时预约" + driverNum + "人");
            }
            order.setMemo(order.getMemo() + ";" + "客户电话：" + order.getClientPhone());
        }

        WeixinManager weixinManager = null;

        if (null != weixinManagerId) {
            weixinManager = weixinManagerMapper.selectByPrimaryKey(weixinManagerId);
            if (null != weixinManager) {
                if (StringUtils.isBlank(order.getMemo())) {
                    order.setMemo("选择了客户经理" + weixinManager.getName() + "下单，使用客户经理收费标准");
                } else {
                    order.setMemo(order.getMemo() + ";" + "选择了客户经理" + weixinManager.getName()
                        + "下单，使用客户经理收费标准");
                }
            }
        }

        List<Order> orders = new LinkedList<Order>();
        for (int i = 1; i <= driverNum; i++) {
            final Order dborder = new Order();
            BeanUtils.copyProperties(order, dborder);
            dborder.setStatus(0);
            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                dborder.setMemberType(Order.ORDER_MEMBER_TYPE_PASSENGER);
            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                dborder.setMemberType(Order.ORDER_MEMBER_TYPE_ENTERPRISE);
            }

            // 生成订单号
            StringBuilder sb = new StringBuilder();
            sb.append(OrderNumberConfig.FROMWEB);// web生成
            if (null != passenger && passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                sb.append(OrderNumberConfig.COMPANY);// 企业用户
            } else {
                sb.append(OrderNumberConfig.CUSTOMER);// 普通用户
            }
            sb.append(format.format(new Date()));// 年月日时间
            sb.append(OrderNumberConfig.padZero(orderMapper.getRunningNumber() + 1));// 流水号
            dborder.setOrderNumber(sb.toString());
            dborder.setDriverId(drivers.get(i - 1).getId());
            dborder.setDriverName(drivers.get(i - 1).getName());
            dborder.setDriverRealName(drivers.get(i - 1).getRealname());
            dborder.setDriverPhone(drivers.get(i - 1).getPhone());
            dborder.setStatus(1);
            dborder.setIsClosed(true);

            // 优惠券
            if (null != couponIds && couponIds.length > 0) {
                if (couponIds.length >= i) {
                    Coupon coupon = salesApi.findOneCoupon(couponIds[i - 1]).getResult();
                    if (null != coupon && coupon.getStatus().equals(Coupon.COUPON_STATUS_NOTUSE)) {
                        coupon.setStatus(Coupon.COUPON_STATUS_HASUSED);
                        salesApi.updateCoupon(coupon);
                        dborder.setCouponId(coupon.getId());
                    }
                }
            }

            orderMapper.insertRecord(dborder);

            if (null != weixinManager) {
                WeixinManagerXOrder wxo = new WeixinManagerXOrder();
                wxo.setManagerId(weixinManager.getId());
                wxo.setOrderId(dborder.getId());
                wxo.setOrderNumber(dborder.getOrderNumber());
                wxo.setMemo(dborder.getMemo());
                weixinManagerXOrderMapper.insertRecord(wxo);
            }

            // 设置服务人员为接单
            Driver driver = drivers.get(i - 1);
            driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_APPLY_ORDER,
                Driver.DRIVER_JOBSTATUS_DAIJIA, driver.getId());
            driver.setStatus(Driver.DRIVER_APPLY_ORDER);

            // 扣费
            Setting setting = settingUtils.get();

            if (setting.getInfoFee() != 0) {
                if (null != setting.getInfoFeeType() && setting.getInfoFeeType()
                    .equals(InfoFeeType.paidan)) {
                    // 执行扣费
                    driver.setVirtual(
                        driver.getVirtual().subtract(new BigDecimal(setting.getInfoFee())));
                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                    // 扣费记录
                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                    driverPaymentsRecord.setMoney(new BigDecimal(setting.getInfoFee()));
                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                    driverPaymentsRecord
                        .setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                    driverPaymentsRecord.setDriverId(driver.getId());
                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                    driverPaymentsRecord.setOrderId(dborder.getId());
                    driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                    driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                    driverPaymentsRecord.setMemo("扣除公司所得保险费/信息费" + setting.getInfoFee() + "元。");
                    driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                    driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                    driverPaymentsRecord.setHappend(new Date());
                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                    // 财务记录（保险费/信息费）
                    Company mainCompany = companyMapper.selectMainCompany();
                    DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                    FinancialRecord financialRecord = new FinancialRecord();
                    StringBuilder sb_f = new StringBuilder();
                    sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 报销金额
                    sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                    sb_f.append(format_f.format(new Date()));// 年月日时间
                    sb_f.append(OrderNumberConfig
                        .padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                    financialRecord.setCode(sb_f.toString());
                    financialRecord.setCompanyId(mainCompany.getId());
                    financialRecord.setCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setOrderCompanyId(mainCompany.getId());
                    financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setMemo(
                        "订单号【<a target='_blank' href='/order/detail/" + dborder.getId() + "'>"
                            + dborder.getOrderNumber() + "</a>】保险费/信息费");
                    financialRecord.setMoney(new BigDecimal(setting.getInfoFee()));
                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                    financialRecord.setWho(driver.getRealname());
                    financialRecord.setOrderId(dborder.getId());
                    financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                    financialRecordMapper.insertRecord(financialRecord);
                }
            }

            // 添加一条订单状态
            OrderStatus os = new OrderStatus();
            os.setOrderId(dborder.getId());
            os.setStatusType(StatusType.neworder);
            if (order.getOrderType().equals(Order.ORDER_TYPE_PHONE)) {
                os.setContent("管理员【" + principal.getUsername() + "】下单");
            } else if (order.getOrderType().equals(Order.ORDER_TYPE_APP)) {
                os.setContent("客户【" + order.getClientName() + "】下单");
            }
            os.setHappened(new Date());
            orderStatusMapper.insertRecord(os);

            // 添加一条订单状态
            os = new OrderStatus();
            os.setOrderId(dborder.getId());
            os.setStatusType(StatusType.paidan);
            os.setContent("【" + principal.getUsername() + "】派单给服务人员：" + driver.getRealname());
            os.setHappened(new Date());
            orderStatusMapper.insertRecord(os);

            orders.add(dborder);

        }

        Setting setting = settingUtils.get();

        for (Order order2 : orders) {
            OrderInputHistoryEvent inputHistoryEvent = new OrderInputHistoryEvent(order2);
            applicationEventMulticaster.multicastEvent(inputHistoryEvent);
            if (order2.getDriverId() != null) {
                OrderPaidanEvent paidanEvent = new OrderPaidanEvent(order2);
                applicationEventMulticaster.multicastEvent(paidanEvent);
            }
            OrderRecordEvent orderRecordEvent = new OrderRecordEvent(order2);
            applicationEventMulticaster.multicastEvent(orderRecordEvent);

            // 自动收回
            if (setting.getRevokeTime() != 0) {
                try {
                    // 订单自动收回定时器
                    Timer timer = new Timer();
                    OrderRevokeTimerTask orderRevokeTimerTask = new OrderRevokeTimerTask(
                        order2.getId(), "daijia",
                        applicationEventMulticaster);
                    Integer howLong = setting.getRevokeTime();
                    timer.schedule(orderRevokeTimerTask, howLong * 1000);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }

        return orders;
    }

    // 代驾预算价格
    @Override
    public Map<String, Object> getPrice(String ack, Long passengerId, Double startLat,
        Double startLng, Double endLat,
        Double endLng) {

        Map<String, Object> map = new HashMap<String, Object>();
        Area area = null;
        Long companyId = null;

        if (null != passengerId) {
            Passenger passenger = memberService.findOnePassenger(passengerId);
            if (null != passenger) {
                companyId = passenger.getCompanyId();
            }
        }

        if (StringUtils.isNotBlank(ack)) {
            Company ackCompany = companyMapper.selectByAppKey(ack);
            if (null != ackCompany) {
                area = areaMapper.selectByPrimaryKey(ackCompany.getAreaId());
            }
        }

        if (null != area) {
            area = areaMapper.selectByPrimaryKeyWithCharge(area.getId());
        } else {
            List<Company> companyList = null;
            String city = HttpClientUtil.getCityByLngAndLat(startLng, startLat);
            if (StringUtils.isNotBlank(city)) {
                companyList = companyMapper.selectByAreaCityName(city);
            }
            Company company = null;
            if (!CollectionUtils.isEmpty(companyList)) {
                for (Company c : companyList) {
                    if (null != companyId && c.getId().equals(companyId)) {
                        company = c;
                        break;
                    }
                }

                List<Company> notMainCompanys = new ArrayList<Company>();
                Company cityMainCompany = null;

                if (null == company) {
                    for (Company c : companyList) {
                        if (!c.isCompanyType()) {
                            if (StringUtils.isBlank(c.getAppKey())) {
                                notMainCompanys.add(c);
                            }
                        } else {
                            cityMainCompany = c;
                        }
                    }
                    if (!CollectionUtils.isEmpty(notMainCompanys)) {
                        company = notMainCompanys.get(new Random().nextInt(notMainCompanys.size()));
                    }
                }
                if (null == company) {
                    if (null != cityMainCompany) {
                        company = cityMainCompany;
                    }
                }
            }
            if (null == company) {
                company = companyMapper.selectMainCompany();
            }
            area = areaMapper.selectByPrimaryKeyWithCharge(company.getAreaId());
        }

        Long distance = 0L;
        Long time = 0L;

        if (null != endLng && null != endLat) {
            Result<Map<String, Long>> result = HttpClientUtil
                .getDistanceAndTimeValueByTwoPoints(startLng, startLat,
                    endLng, endLat);
            Map<String, Long> result2 = result.getResult();
            distance = result2.get("distance");// 米
            time = result2.get("time");// 秒
        }

        Long travelTime = 0L;
        Double mileage = 0.0;
        if (time != null) {
            travelTime = time / 60;
        }
        if (distance != null) {
            mileage = Double.valueOf(distance / 1000);
        }
        BigDecimal money = BigDecimal.ZERO;

        SelectPrice selectPrice = new SelectPrice();
        selectPrice.setPrice(travelTime, mileage, area, null, null);

        money = selectPrice.shouldCash;
        BigDecimal startPrice = selectPrice.qbCost;

        BigDecimal travelTimePrice = selectPrice.getTravalTimeCost();
        BigDecimal mileagePrice = selectPrice.getDisCost();

        ChargeStartTime price = selectPrice.getPrice();
        StringBuilder builder = new StringBuilder();
        builder.append("起步价:" + startPrice + "元\n");
        List<ChargeStartDistance> distances = price.getChargeStartDistances();

        if (distances != null && distances.size() != 0) {
            for (ChargeStartDistance d : distances) {
                builder.append(
                    d.getStartdistance() + "公里到" + d.getDistance() + "公里内,加收" + d.getMoney() + "元");
                builder.append("\n");
            }
        }

        builder.append("超过" + price.getQblc() + "公里");
        builder.append("以后每" + price.getDjglUnit() + "公里");
        builder.append("加收" + price.getDjglCost() + "元");
        if (price.getDjglThresholdt() != 0) {
            builder.append("(不足" + price.getDjglThresholdt() + "公里不计费)");
        }
        builder.append("\n");
        builder.append("起步后" + price.getQbsj() + "分钟内不收费");
        builder.append("以后每" + price.getDjsjUnit() + "分钟");
        builder.append("加收" + price.getDjsjCost() + "元");
        if (price.getDjsjThresholdt() != 0) {
            builder.append("(不足" + price.getDjsjThresholdt() + "分钟不收费)");
        }
        builder.append("\n");
        builder.append("免费等候" + price.getMfdhsj() + "分钟");
        BigDecimal bigDecimal = price.getDhsjAtonceCost();

        if (bigDecimal.compareTo(BigDecimal.ZERO) == 1) {
            builder.append("到达则立即加收" + price.getDhsjAtonceCost() + "元");
        }
        builder.append("后每" + price.getDhsjUnit() + "分钟");
        builder.append("加收" + price.getDhsjCost() + "元");
        if (price.getDhsjThresholdt() != 0) {
            builder.append("(低于" + price.getDhsjThresholdt() + "分钟不计费)");
        }
        builder.append("\n");
        if (StringUtils.isNotBlank(area.getMemo())) {
            builder.append("备注:" + area.getMemo());
        }
        String pay_detail = builder.toString();

        map.put("success", true);
        map.put("message", "请求成功");
        map.put("money", money);
        map.put("travelTime", travelTime); // 执行时间 分钟
        map.put("time", travelTime); // 执行时间 分钟
        map.put("startPrice", startPrice != null ? startPrice.doubleValue() : 0); // 起步价
        map.put("mileage", mileage); // 行驶里程 公里
        map.put("mileagePrice", mileagePrice != null ? mileagePrice.doubleValue() : 0); // 行驶里程费用
        map.put("travelTimePrice",
            travelTimePrice != null ? travelTimePrice.doubleValue() : 0); // 服务时间费用
        map.put("pay_detail", pay_detail);
        return map;
    }

    @Override
    public Map<String, Object> getNewPrice(String ack, Long passengerId, Integer time,
        Double mileage, Double startLat,
        Double startLng) {
        Map<String, Object> map = new HashMap<String, Object>();
        Area area = null;
        if (StringUtils.isNotBlank(ack)) {
            Company ackCompany = companyMapper.selectByAppKey(ack);
            if (null != ackCompany) {
                area = areaMapper.selectByPrimaryKey(ackCompany.getAreaId());
            }
        }

        Passenger passenger = null;
        if (null == area && passengerId != null && passengerId != 0) {
            passenger = passengerApi.findOnePassenger(passengerId, settingUtils.get()).getResult();
            if (null != passenger && null != passenger.getGrade_id()) {
                PassengerGrade passengerGrade = passengerApi
                    .findOneGrade(passenger.getGrade_id(), settingUtils.get())
                    .getResult();
                if (null != passengerGrade && null != passengerGrade.getDaijiaAreaId()) {
                    area = areaMapper.selectByPrimaryKey(passengerGrade.getDaijiaAreaId());
                }
            }
        }

        if (null != area) {
            area = areaMapper.selectByPrimaryKeyWithCharge(area.getId());
        } else {
            List<Company> companyList = null;
            String city = HttpClientUtil.getCityByLngAndLat(startLng, startLat);
            if (StringUtils.isNotBlank(city)) {
                companyList = companyMapper.selectByAreaCityName(city);
            }
            Company company = null;
            if (!CollectionUtils.isEmpty(companyList)) {
                for (Company c : companyList) {
                    if (null != passenger && c.getId().equals(passenger.getCompanyId())) {
                        company = c;
                        break;
                    }
                }
                List<Company> notMainCompany = new ArrayList<Company>();// 子公司
                if (company == null) {
                    for (Company c : companyList) {
                        if (!c.isCompanyType()) {
                            notMainCompany.add(c);
                        }
                    }
                }
                if (company == null && !CollectionUtils.isEmpty(notMainCompany)) {
                    company = notMainCompany.get(new Random().nextInt(notMainCompany.size()));
                }
            }
            if (company == null) {
                company = companyMapper.selectMainCompany();
            }
            area = areaMapper.selectByPrimaryKeyWithCharge(company.getAreaId());
        }
        BigDecimal money = BigDecimal.ZERO;
        BigDecimal mileagePrice = BigDecimal.ZERO;
        BigDecimal travelTimePrice = BigDecimal.ZERO;

        SelectPrice selectPrice = new SelectPrice();
        if (area == null) {
            map.put("success", false);
            map.put("message", "收费标准为空");
            return map;
        } else {
            selectPrice.setPrice(time, mileage, area, null, null);
        }

        ChargeStartTime price = selectPrice.getPrice();
        BigDecimal startPrice = selectPrice.qbCost;
        money = selectPrice.shouldCash;
        mileagePrice = selectPrice.disCost;
        travelTimePrice = selectPrice.travalTimeCost;
        StringBuilder builder = new StringBuilder();
        builder.append("起步价:" + startPrice + "元\n");
        List<ChargeStartDistance> distances = price.getChargeStartDistances();

        if (distances != null && distances.size() != 0) {
            for (ChargeStartDistance d : distances) {
                builder.append(
                    d.getStartdistance() + "公里到" + d.getDistance() + "公里内,加收" + d.getMoney() + "元");
                builder.append("\n");
            }
        }

        builder.append("超过" + price.getQblc() + "公里");
        builder.append("以后每" + price.getDjglUnit() + "公里");
        builder.append("加收" + price.getDjglCost() + "元");
        if (price.getDjglThresholdt() != 0) {
            builder.append("(不足" + price.getDjglThresholdt() + "公里不计费)");
        }
        builder.append("\n");
        builder.append("起步后" + price.getQbsj() + "分钟内不收费");
        builder.append("以后每" + price.getDjsjUnit() + "分钟");
        builder.append("加收" + price.getDjsjCost() + "元");
        if (price.getDjsjThresholdt() != 0) {
            builder.append("(不足" + price.getDjsjThresholdt() + "分钟不收费)");
        }
        builder.append("\n");
        builder.append("免费等候" + price.getMfdhsj() + "分钟");
        BigDecimal bigDecimal = price.getDhsjAtonceCost();

        if (bigDecimal.compareTo(BigDecimal.ZERO) == 1) {
            builder.append("到达则立即加收" + price.getDhsjAtonceCost() + "元");
        }
        builder.append("后每" + price.getDhsjUnit() + "分钟");
        builder.append("加收" + price.getDhsjCost() + "元");
        if (price.getDhsjThresholdt() != 0) {
            builder.append("(低于" + price.getDhsjThresholdt() + "分钟不计费)");
        }
        builder.append("\n");
        if (StringUtils.isNotBlank(area.getMemo())) {
            builder.append("备注:" + area.getMemo());
        }
        String pay_detail = builder.toString();

        map.put("success", true);
        map.put("message", "请求成功");
        map.put("money", money);
        map.put("startPrice", startPrice != null ? startPrice.doubleValue() : 0); // 起步价
        map.put("mileagePrice", mileagePrice != null ? mileagePrice.doubleValue() : 0); // 行驶里程费用
        map.put("travelTimePrice",
            travelTimePrice != null ? travelTimePrice.doubleValue() : 0); // 服务时间费用
        map.put("pay_detail", pay_detail);
        return map;
    }

    @Override
    public Map<String, Object> getMyPrice(Integer time, Double mileage, Driver driver, String phone,
        Long areaId) {
        Map<String, Object> map = new HashMap<String, Object>();
        Area area = null;
        if (null != areaId) {
            AreaOfEmploy areaOfEmploy = areaOfEmployMapper.selectByPrimaryKeyWithCharge(areaId);
            if (null != areaOfEmploy) {
                area = new Area();
                List<ChargeStartTime> csts = new ArrayList<ChargeStartTime>();
                if (!CollectionUtils.isEmpty(areaOfEmploy.getChargeStartTimes())) {
                    for (ChargeStartTimeOfEmploy chargeStartTimeOfEmploy : areaOfEmploy
                        .getChargeStartTimes()) {
                        ChargeStartTime cst = new ChargeStartTime();
                        BeanUtils.copyProperties(chargeStartTimeOfEmploy, cst);
                        csts.add(cst);
                    }
                }
                area.setChargeStartTimes(csts);
            }
        }

        if (null == area && StringUtils.isNotBlank(phone)) {
            Passenger passenger = passengerApi.findOnePassengerByPhone(phone, settingUtils.get())
                .getResult();
            if (null != passenger) {
                if (null != passenger.getGrade_id()) {
                    PassengerGrade passengerGrade = passengerApi
                        .findOneGrade(passenger.getGrade_id(), settingUtils.get()).getResult();
                    if (null != passengerGrade) {
                        if (null != passengerGrade.getDaijiaAreaId()) {
                            area = areaMapper
                                .selectByPrimaryKeyWithCharge(passengerGrade.getDaijiaAreaId());
                        }
                    }
                }
            }
        }

        if (null == area) {
            Company company = companyMapper.selectByPrimaryKey(driver.getCompanyId());
            area = areaMapper.selectByPrimaryKeyWithCharge(company.getAreaId());
        }

        BigDecimal money = BigDecimal.ZERO;
        BigDecimal mileagePrice = BigDecimal.ZERO;
        BigDecimal travelTimePrice = BigDecimal.ZERO;

        SelectPrice selectPrice = new SelectPrice();
        selectPrice.setPrice(time, mileage, area, null, null);

        ChargeStartTime price = selectPrice.getPrice();
        BigDecimal startPrice = selectPrice.qbCost;
        money = selectPrice.shouldCash;
        mileagePrice = selectPrice.disCost;
        travelTimePrice = selectPrice.travalTimeCost;
        StringBuilder builder = new StringBuilder();
        builder.append("起步价:" + startPrice + "元\n");
        List<ChargeStartDistance> distances = price.getChargeStartDistances();

        if (distances != null && distances.size() != 0) {
            for (ChargeStartDistance d : distances) {
                builder.append(
                    d.getStartdistance() + "公里到" + d.getDistance() + "公里内,加收" + d.getMoney() + "元");
                builder.append("\n");
            }
        }

        builder.append("超过" + price.getQblc() + "公里");
        builder.append("以后每" + price.getDjglUnit() + "公里");
        builder.append("加收" + price.getDjglCost() + "元");
        if (price.getDjglThresholdt() != 0) {
            builder.append("(不足" + price.getDjglThresholdt() + "公里不计费)");
        }
        builder.append("\n");
        builder.append("起步后" + price.getQbsj() + "分钟内不收费");
        builder.append("以后每" + price.getDjsjUnit() + "分钟");
        builder.append("加收" + price.getDjsjCost() + "元");
        if (price.getDjsjThresholdt() != 0) {
            builder.append("(不足" + price.getDjsjThresholdt() + "分钟不收费)");
        }
        builder.append("\n");
        builder.append("免费等候" + price.getMfdhsj() + "分钟");
        BigDecimal bigDecimal = price.getDhsjAtonceCost();

        if (bigDecimal.compareTo(BigDecimal.ZERO) == 1) {
            builder.append("到达则立即加收" + price.getDhsjAtonceCost() + "元");
        }
        builder.append("后每" + price.getDhsjUnit() + "分钟");
        builder.append("加收" + price.getDhsjCost() + "元");
        if (price.getDhsjThresholdt() != 0) {
            builder.append("(低于" + price.getDhsjThresholdt() + "分钟不计费)");
        }
        builder.append("\n");
        if (StringUtils.isNotBlank(area.getMemo())) {
            builder.append("备注:" + area.getMemo());
        }
        String pay_detail = builder.toString();

        map.put("success", true);
        map.put("message", "请求成功");
        map.put("money", money);
        map.put("startPrice", startPrice != null ? startPrice.doubleValue() : 0); // 起步价
        map.put("mileagePrice", mileagePrice != null ? mileagePrice.doubleValue() : 0); // 行驶里程费用
        map.put("travelTimePrice",
            travelTimePrice != null ? travelTimePrice.doubleValue() : 0); // 服务时间费用
        map.put("pay_detail", pay_detail);
        return map;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Order> create(Order order, Integer driverNum, Long[] couponIds, Double longitude,
        Double latitude,
        Long companyId, Long weixinManagerId, BigDecimal fixPriceMoney, BigDecimal yuguMoney) {
        // 将订单封装斤Result结果集里
        Result<Order> result = new Result<Order>();
        // 查询商户私钥
        Company company = companyMapper.selectByPrimaryKey(companyId);

        // 根据客户电话查询客户
        Result<Passenger> result_p = passengerApi
            .findOnePassengerByPhone(order.getClientPhone(), settingUtils.get());
        // 这个是老乘客数据
        Passenger passenger = result_p.getResult();
        if (null != passenger) {
            // 老客户 更新位置
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            if (!StringUtils.isBlank(order.getClientName()) && StringUtils
                .isBlank(passenger.getName())) {
                passenger.setName(order.getClientName());
                passengerApi.updatePersonal(passenger, settingUtils.get());
            }
        } else {
            // 新客户
            passenger = new Passenger();
            passenger.setName(order.getClientName());
            passenger.setPhone(order.getClientPhone());
            passenger.setChannel_name(order.getFromSource());
            passenger.setType(Passenger.TYPE_PASSENGER);
            passenger.setAllowOverdraw(false);
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            passenger.setCompanyId(company.getId());
            passenger.setCompanyName(company.getAbbreviation());

            Result<Passenger> result_passenger = passengerApi
                .createPersonal(passenger, settingUtils.get());
            if (result_passenger.isSuccess()) {
                passenger = result_passenger.getResult();
            } else {
                result.setSuccess(false);
                result.setMessage(result_passenger.getMessage());
                return result;
            }
        }

        DateFormat format = new SimpleDateFormat("yyyyMMdd");

        order.setCompanyId(company.getId());
        order.setDjxFee(company.getDjxFee());
        order.setYwxFee(company.getYwxFee());
        order.setManagerId(weixinManagerId);

        if (order.isFixPrice()) {
            order.setShouldCash(fixPriceMoney);
        } else {
            order.setShouldCash(yuguMoney);
        }

        order.setClientLongitude(longitude);
        order.setClientLatitude(latitude);

        order.setClientId(passenger.getId());
        if (StringUtils.isBlank(order.getClientName())) {
            order.setClientName(passenger.getName());
        }

        if (passenger.isInBlackList()) {
            order.setMemo("黑名单客户");
        }

        if (driverNum > 1) {
            OrderGroup orderGroup = new OrderGroup();
            orderGroupMapper.insertRecord(orderGroup);
            order.setOrderGroupId(orderGroup.getId());
            if (StringUtils.isBlank(order.getMemo())) {
                order.setMemo("客户同时预约" + driverNum + "人");
            } else {
                order.setMemo(order.getMemo() + ";" + "客户同时预约" + driverNum + "人");
            }
            order.setMemo(order.getMemo() + ";" + "客户电话：" + order.getClientPhone());
        }

        WeixinManager weixinManager = null;

        if (null != weixinManagerId) {
            weixinManager = weixinManagerMapper.selectByPrimaryKey(weixinManagerId);
            if (null != weixinManager) {
                if (StringUtils.isBlank(order.getMemo())) {
                    order.setMemo("选择了客户经理" + weixinManager.getName() + "下单，使用客户经理收费标准");
                } else {
                    order.setMemo(order.getMemo() + ";" + "选择了客户经理" + weixinManager.getName()
                        + "下单，使用客户经理收费标准");
                }
            }
        }

        List<Order> newOrders = new ArrayList<Order>();
        for (int i = 1; i <= driverNum; i++) {
            Order dborder = new Order();
            BeanUtils.copyProperties(order, dborder);
            dborder.setStatus(0);
            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                dborder.setMemberType(Order.ORDER_MEMBER_TYPE_PASSENGER);
            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                dborder.setMemberType(Order.ORDER_MEMBER_TYPE_ENTERPRISE);
            }

            // 生成订单号
            StringBuilder sb = new StringBuilder();
            sb.append(OrderNumberConfig.FROMWEB);// web生成
            if (null != passenger && passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                sb.append(OrderNumberConfig.COMPANY);// 企业用户
            } else {
                sb.append(OrderNumberConfig.CUSTOMER);// 普通用户
            }
            sb.append(format.format(new Date()));// 年月日时间
            sb.append(OrderNumberConfig.padZero(orderMapper.getRunningNumber() + 1));// 流水号
            dborder.setOrderNumber(sb.toString());

            // 优惠券
            if (null != couponIds && couponIds.length > 0) {
                if (couponIds.length >= i) {
                    Coupon coupon = salesApi.findOneCoupon(couponIds[i - 1]).getResult();
                    if (null != coupon && coupon.getStatus().equals(Coupon.COUPON_STATUS_NOTUSE)) {
                        coupon.setStatus(Coupon.COUPON_STATUS_HASUSED);
                        salesApi.updateCoupon(coupon);
                        dborder.setCouponId(coupon.getId());
                    }
                }
            }

            orderMapper.insertRecord(dborder);

            // 醉无忧 - 人保新加
            if (null != dborder.getOrderNoRenBao() && null != dborder.getCuponNoRenBao()) {
                // 新单推送
                zWYApi.syncOrderInfo(dborder.getOrderNoRenBao(), dborder.getCuponNoRenBao(),
                    dborder.getOrderNumber(),
                    String.valueOf(0), dborder.getClientPhone());
                // 锁定凭证码
                zWYApi.cuponnoLock(dborder.getOrderNoRenBao(), dborder.getCuponNoRenBao(),
                    dborder.getOrderNumber(),
                    dborder.getClientPhone());
            }

            newOrders.add(dborder);
            if (null != weixinManager) {
                WeixinManagerXOrder wxo = new WeixinManagerXOrder();
                wxo.setManagerId(weixinManager.getId());
                wxo.setOrderId(dborder.getId());
                wxo.setOrderNumber(dborder.getOrderNumber());
                wxo.setMemo(dborder.getMemo());
                weixinManagerXOrderMapper.insertRecord(wxo);
            }

            // 添加一条订单状态
            OrderStatus os = new OrderStatus();
            os.setOrderId(dborder.getId());
            os.setStatusType(StatusType.neworder);
            if (order.getOrderType().equals(Order.ORDER_TYPE_PHONE)) {
                Subject currentUser = SecurityUtils.getSubject();
                Principal principal = (Principal) currentUser.getPrincipal();
                os.setContent("管理员【" + principal.getUsername() + "】下单");
            } else if (order.getOrderType().equals(Order.ORDER_TYPE_APP)) {
                os.setContent("客户【" + order.getClientName() + "】下单");
            } else if (order.getOrderType().equals(Order.ORDER_TYPE_XCX)) {
                os.setContent("客户【" + order.getClientName() + "】下单");
            } else if (order.getOrderType().equals(Order.ORDER_TYPE_WEIXIN)) {
                os.setContent("客户【" + order.getClientName() + "】下单");
            }
            os.setHappened(new Date());
            orderStatusMapper.insertRecord(os);
        }
        result.setSuccess(true);
        result.setData(newOrders);
        return result;

    }

    @Transactional(rollbackFor = Exception.class)
    public void paidan(Driver driver, Order order) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Setting setting = settingUtils.get();

        order.setDriverId(driver.getId());
        order.setDriverName(driver.getName());
        order.setDriverRealName(driver.getRealname());
        order.setDriverPhone(driver.getPhone());
        order.setStatus(Order.ORDER_STATUS_YIPAIDAN);
        orderMapper.updateByPrimaryKey(order);

        // 设置服务人员为接单
        driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_APPLY_ORDER,
            Driver.DRIVER_JOBSTATUS_DAIJIA,
            driver.getId());

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.paidan);
        os.setContent("【" + principal.getUsername() + "】派单给服务人员：" + driver.getRealname());
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        // 手动派单后取消自动派单
        try {
            Timer timer = ThreadControl.TaskMaps.get("task_" + order.getId());
            if (null != timer) {
                timer.cancel();
                ThreadControl.TaskMaps.remove("task_" + order.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 自动收回
        if (setting.getRevokeTime() != 0) {
            try {
                // 专车订单自动收回定时器
                Timer timer = new Timer();
                OrderRevokeTimerTask orderRevokeTimerTask = new OrderRevokeTimerTask(order.getId(),
                    "daijia",
                    applicationEventMulticaster);
                Integer howLong = setting.getRevokeTime();
                timer.schedule(orderRevokeTimerTask, howLong * 1000);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public synchronized int autoPaidan(Driver tmpDriver, Order order) {

        Driver driver = driverMapper.selectByPrimaryKey(tmpDriver.getId());

        Setting setting = settingUtils.get();

        if (driver.getStatus().equals(Driver.DRIVER_ONLINE)) {
            // 设置服务人员为接单
            int i = driverMapper
                .updateStatusAndJobStatusForOnlinedByPrimaryKey(Driver.DRIVER_APPLY_ORDER,
                    Driver.DRIVER_JOBSTATUS_DAIJIA, driver.getId());
            if (i == 0) {
                return 0;
            }
            order.setDriverId(driver.getId());
            order.setDriverName(driver.getName());
            order.setDriverRealName(driver.getRealname());
            order.setDriverPhone(driver.getPhone());
            order.setStatus(Order.ORDER_STATUS_YIPAIDAN);
            orderMapper.updateByPrimaryKey(order);

            // 添加一条订单状态
            OrderStatus os = new OrderStatus();
            os.setOrderId(order.getId());
            os.setStatusType(StatusType.paidan);
            os.setContent("【系统】自动派单给服务人员：" + driver.getRealname());
            os.setHappened(new Date());
            orderStatusMapper.insertRecord(os);

            // 日志
            Company company = companyMapper.selectByPrimaryKey(order.getCompanyId());
            OperationLog log = new OperationLog();
            log.setCompamyId(company.getId());
            log.setCompanyName(company.getAbbreviation());
            log.setOperating("系统");
            log.setHost("-");
            log.setDetail(
                "系统自动派单【" + order.getOrderNumber() + "】给服务人员：【" + driver.getRealname() + "】");
            operationLogMapper.insertRecord(log);

            // 自动收回
            if (setting.getRevokeTime() != 0) {
                try {
                    // 代驾订单自动收回定时器
                    Timer timer = new Timer();
                    OrderRevokeTimerTask orderRevokeTimerTask = new OrderRevokeTimerTask(
                        order.getId(), "daijia",
                        applicationEventMulticaster);
                    Integer howLong = setting.getRevokeTime();
                    timer.schedule(orderRevokeTimerTask, howLong * 1000);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }

            return 1;
        } else {
            return 0;
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public synchronized void yupaidan(Driver driver, Order order, String type) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        order.setDriverId(driver.getId());
        order.setDriverName(driver.getName());
        order.setDriverRealName(driver.getRealname());
        order.setDriverPhone(driver.getPhone());
        if (driver.getStatus().equals(Driver.DRIVER_ONLINE)) {
            order.setStatus(Order.ORDER_STATUS_YIPAIDAN);
        } else {
            order.setStatus(Order.ORDER_STATUS_YUPAIDAN);
        }
        orderMapper.updateByPrimaryKey(order);

        // 设置服务人员为接单
        if (driver.getStatus().equals(Driver.DRIVER_ONLINE)) {
            driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_APPLY_ORDER,
                Driver.DRIVER_JOBSTATUS_DAIJIA, driver.getId());
        }

        // 扣费
        Setting setting = settingUtils.get();

        if (setting.getInfoFee() != 0) {
            if (driver.getStatus().equals(Driver.DRIVER_ONLINE) && null != setting.getInfoFeeType()
                && setting.getInfoFeeType().equals(InfoFeeType.paidan)) {
                driver
                    .setVirtual(driver.getVirtual().subtract(new BigDecimal(setting.getInfoFee())));
                driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                // 扣费记录
                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                driverPaymentsRecord.setMoney(new BigDecimal(setting.getInfoFee()));
                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                driverPaymentsRecord.setDriverId(driver.getId());
                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                driverPaymentsRecord.setOrderId(order.getId());
                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                driverPaymentsRecord.setMemo("扣除公司所得保险费/信息费" + setting.getInfoFee() + "元。");
                driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                driverPaymentsRecord.setHappend(new Date());
                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                // 财务记录（保险费/信息费）
                Company mainCompany = companyMapper.selectMainCompany();
                DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb_f = new StringBuilder();
                sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 保险费/信息费
                sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                sb_f.append(format_f.format(new Date()));// 年月日时间
                sb_f.append(
                    OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                financialRecord.setCode(sb_f.toString());
                financialRecord.setCompanyId(mainCompany.getId());
                financialRecord.setCompanyName(mainCompany.getAbbreviation());
                financialRecord.setOrderCompanyId(mainCompany.getId());
                financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                financialRecord
                    .setMemo("订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                        + order.getOrderNumber() + "</a>】保险费/信息费");
                financialRecord.setMoney(new BigDecimal(setting.getInfoFee()));
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                financialRecord.setWho(driver.getRealname());
                financialRecord.setOrderId(order.getId());
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                financialRecordMapper.insertRecord(financialRecord);
            }
        }

        if (null != type && "man".equals(type)) {
            // 添加一条订单状态
            OrderStatus os = new OrderStatus();
            os.setOrderId(order.getId());
            os.setStatusType(StatusType.paidan);
            os.setContent("【" + principal.getUsername() + "】派单给服务人员：" + driver.getRealname());
            os.setHappened(new Date());
            orderStatusMapper.insertRecord(os);
        }

        // 取消自动派单定时
        try {
            Timer timer = ThreadControl.TaskMaps.get("task_" + order.getId());
            if (null != timer) {
                timer.cancel();
                ThreadControl.TaskMaps.remove("task_" + order.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void getRushOrder(Driver driver, Order order) {

        order.setDriverId(driver.getId());
        order.setDriverName(driver.getName());
        order.setDriverRealName(driver.getRealname());
        order.setDriverPhone(driver.getPhone());
        order.setStatus(Order.ORDER_STATUS_BUSY);
        orderMapper.updateByPrimaryKey(order);

        if (null != order.getOrderGroupId()) {
            OrderGroup orderGroup = orderGroupMapper.selectByPrimaryKey(order.getOrderGroupId());
            if (null != orderGroup && null == orderGroup.getDriverId()) {
                orderGroup.setDriverId(driver.getId());
                orderGroupMapper.updateByPrimaryKey(orderGroup);
            }
        }

        // 设置服务人员为忙碌
        driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_BUSY,
            Driver.DRIVER_JOBSTATUS_DAIJIA,
            driver.getId());
        driver.setStatus(Driver.DRIVER_BUSY);

        // 扣费
        Company company = companyMapper.selectByPrimaryKey(order.getCompanyId());

        if (null != company.getInfoFeeType()
            && company.getInfoFeeType().compareTo(Company.InfoFeeType.acceptTask) == 0) {
            if (company.getInfoFee().doubleValue() != 0) {
                driver.setVirtual(driver.getVirtual().subtract(company.getInfoFee()));
                driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                // 扣费记录
                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                driverPaymentsRecord.setMoney(company.getInfoFee());
                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                driverPaymentsRecord.setInfoFeeType(DriverPaymentsRecord.INFOFEE_TYPE_INFO);
                driverPaymentsRecord.setDriverId(driver.getId());
                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                driverPaymentsRecord.setOrderId(order.getId());
                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                driverPaymentsRecord.setMemo("扣除公司所得信息费" + company.getInfoFee() + "元。");
                driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                driverPaymentsRecord.setHappend(new Date());
                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                // 财务记录（保险费/信息费）
                Company mainCompany = companyMapper.selectMainCompany();
                DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb_f = new StringBuilder();
                sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 保险费/信息费
                sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                sb_f.append(format_f.format(new Date()));// 年月日时间
                sb_f.append(
                    OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                financialRecord.setCode(sb_f.toString());
                financialRecord.setCompanyId(mainCompany.getId());
                financialRecord.setCompanyName(mainCompany.getAbbreviation());
                financialRecord.setOrderCompanyId(mainCompany.getId());
                financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                financialRecord
                    .setMemo("订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                        + order.getOrderNumber() + "</a>】信息费");
                financialRecord.setMoney(company.getInfoFee());
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                financialRecord.setWho(driver.getRealname());
                financialRecord.setOrderId(order.getId());
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                financialRecordMapper.insertRecord(financialRecord);
            }
            // 代驾险
            if (null != order.getDjxFee() && order.getDjxFee().doubleValue() != 0) {
                driver.setVirtual(driver.getVirtual().subtract(order.getDjxFee()));
                driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                // 扣费记录
                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                driverPaymentsRecord.setMoney(order.getDjxFee());
                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                driverPaymentsRecord.setInfoFeeType(DriverPaymentsRecord.INFOFEE_TYPE_DJX);
                driverPaymentsRecord.setDriverId(driver.getId());
                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                driverPaymentsRecord.setOrderId(order.getId());
                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                driverPaymentsRecord.setMemo("扣除公司所得代驾险" + order.getDjxFee() + "元。");
                driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                driverPaymentsRecord.setHappend(new Date());
                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                // 财务记录（保险费）
                Company mainCompany = companyMapper.selectMainCompany();
                DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb_f = new StringBuilder();
                sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 保险费
                sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                sb_f.append(format_f.format(new Date()));// 年月日时间
                sb_f.append(
                    OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                financialRecord.setCode(sb_f.toString());
                financialRecord.setCompanyId(mainCompany.getId());
                financialRecord.setCompanyName(mainCompany.getAbbreviation());
                financialRecord.setOrderCompanyId(mainCompany.getId());
                financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                financialRecord
                    .setMemo("订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                        + order.getOrderNumber() + "</a>】代驾险");
                financialRecord.setMoney(order.getDjxFee());
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                financialRecord.setWho(driver.getRealname());
                financialRecord.setOrderId(order.getId());
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                financialRecordMapper.insertRecord(financialRecord);

                // 保险记录
                DjInsurance djInsurance = new DjInsurance();
                djInsurance.setInsuranceType(DjInsurance.InsuranceType.djx);
                djInsurance.setMoney(order.getDjxFee());
                djInsurance.setOrderId(order.getId());
                djInsurance.setOrderNo(order.getOrderNumber());
                djInsuranceMapper.insertRecord(djInsurance);

                DjxNoticeEvent djxNoticeEvent = new DjxNoticeEvent(driver, djInsurance);
                applicationEventMulticaster.multicastEvent(djxNoticeEvent);
            }
            // 意外险
            if (null != order.getYwxFee() && order.getYwxFee().doubleValue() != 0) {
                driver.setVirtual(driver.getVirtual().subtract(order.getYwxFee()));
                driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                // 扣费记录
                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                driverPaymentsRecord.setMoney(order.getYwxFee());
                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                driverPaymentsRecord.setInfoFeeType(DriverPaymentsRecord.INFOFEE_TYPE_YWX);
                driverPaymentsRecord.setDriverId(driver.getId());
                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                driverPaymentsRecord.setOrderId(order.getId());
                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                driverPaymentsRecord.setMemo("扣除公司所得意外险" + order.getYwxFee() + "元。");
                driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                driverPaymentsRecord.setHappend(new Date());
                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                // 财务记录（保险费）
                Company mainCompany = companyMapper.selectMainCompany();
                DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb_f = new StringBuilder();
                sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 保险费
                sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                sb_f.append(format_f.format(new Date()));// 年月日时间
                sb_f.append(
                    OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                financialRecord.setCode(sb_f.toString());
                financialRecord.setCompanyId(mainCompany.getId());
                financialRecord.setCompanyName(mainCompany.getAbbreviation());
                financialRecord.setOrderCompanyId(mainCompany.getId());
                financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                financialRecord
                    .setMemo("订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                        + order.getOrderNumber() + "</a>】意外险");
                financialRecord.setMoney(order.getYwxFee());
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                financialRecord.setWho(driver.getRealname());
                financialRecord.setOrderId(order.getId());
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                financialRecordMapper.insertRecord(financialRecord);

                // 保险记录
                DjInsurance djInsurance = new DjInsurance();
                djInsurance.setInsuranceType(DjInsurance.InsuranceType.ywx);
                djInsurance.setMoney(order.getYwxFee());
                djInsurance.setOrderId(order.getId());
                djInsurance.setOrderNo(order.getOrderNumber());
                djInsuranceMapper.insertRecord(djInsurance);

                YwxNoticeEvent ywxNoticeEvent = new YwxNoticeEvent(driver, djInsurance);
                applicationEventMulticaster.multicastEvent(ywxNoticeEvent);
            }
        }

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.paidan);
        os.setContent("服务人员【" + driver.getRealname() + "】抢单");
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.accept);
        os.setContent("【" + driver.getRealname() + "】接受订单");
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        OrderRushEvent rushEvent = new OrderRushEvent(order);
        applicationEventMulticaster.multicastEvent(rushEvent);

        // 取消自动派单定时
        try {
            Timer timer = ThreadControl.TaskMaps.get("task_" + order.getId());
            if (null != timer) {
                timer.cancel();
                ThreadControl.TaskMaps.remove("task_" + order.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 派单、调度订单
     **/
    @Override
    public List<Order> listNewOrders(Integer limit) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        if (!principal.isCompanyType()) {
            return orderMapper.selectDiaoduByCompany(principal.getCompanyId(), 0, limit);
        } else {
            return orderMapper.selectDiaoduByCompany(null, 0, limit);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void cancel(Order order, String content) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Integer oldOrderStatus = order.getStatus();
        Long driverid = order.getDriverId();

        // 更新订单为销单
        order.setStatus(Order.ORDER_STATUS_CANCELED);
        order.setDriverId(null);
        order.setDriverName(null);
        order.setDriverRealName(null);
        order.setDriverPhone(null);
        order.setArrivePlaceDate(null);
        order.setStartDriveDate(null);
        orderMapper.updateByPrimaryKey(order);

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.xiaodan);
        os.setContent("【" + principal.getUsername() + "】取消了该订单");
        os.setMemo(content);
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        Driver driver = null;
        if (null != driverid) {
            driver = driverMapper.selectByPrimaryKey(driverid);
        }

        Integer oldDriverStatus = null;
        if (null != driver) {
            oldDriverStatus = driver.getStatus();
        }

        if (null != driver) {
            if (oldOrderStatus != Order.ORDER_STATUS_YUPAIDAN) {
                if (oldDriverStatus != Driver.DRIVER_OFFLINE) {
                    driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null,
                        driver.getId());
                    driver.setStatus(Driver.DRIVER_ONLINE);
                }
            }
        }

        // 销单退款
        if (null != order.getPrePayTypeDetail() && !order.getPrePayTypeDetail()
            .equals(PayTypeDetails.coupon)) {
            Result<Passenger> result_p = passengerApi
                .findOnePassenger(order.getClientId(), settingUtils.get());
            Passenger passenger = result_p.getResult();
            if (null != passenger) {
                BigDecimal coupon_hasPayed = BigDecimal.ZERO;
                if (null != order.getCouponId()) {
                    Coupon coupon = salesApi.findOneCoupon(order.getCouponId()).getResult();
                    if (null != coupon) {
                        if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DEDUCTION)) {
//                            coupon_hasPayed = coupon.getCouponRule().getMoney();
                            coupon_hasPayed = coupon.getCouponPrice();
                        } else if (coupon.getCouponRule().getType()
                            .equals(CouponRule.TYPE_DISCOUNT)) {
//                            Double discount = coupon.getCouponRule().getDiscount();
                            Double discount = coupon.getCouponDiscount();
                            coupon_hasPayed = order.getShouldCash()
                                .multiply(new BigDecimal(1)
                                    .subtract(new BigDecimal(discount).divide(new BigDecimal(10))))
                                .setScale(0, BigDecimal.ROUND_DOWN);
                        }
                    }
                }
                BigDecimal tuikuan = order.getShouldCash().subtract(coupon_hasPayed);
                if (tuikuan.doubleValue() > 0) {
                    if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                        passengerApi.createPassengerAccount(passenger, null, tuikuan,
                            PassengerAccount.PayType.RECHARGE_TYPE_CANCEL_RETURN,
                            PassengerAccount.OPERATING_SYS,
                            "销单退款:" + content, order.getId(), order.getOrderNumber(),
                            PassengerAccount.ORDER_TYPE_DAIJIA, null, true, false,
                            settingUtils.get());
                    } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                        Enterprise enterprise = passengerApi
                            .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                            .getResult();
                        if (null != enterprise) {
                            passengerApi.createEnterpriseAccount(enterprise, tuikuan,
                                PassengerAccount.PayType.RECHARGE_TYPE_CANCEL_RETURN,
                                PassengerAccount.OPERATING_SYS, "销单退款:" + content, order.getId(),
                                order.getOrderNumber(), PassengerAccount.ORDER_TYPE_DAIJIA, null,
                                true, false,
                                settingUtils.get());
                        }
                    }
                }

            }
        }

        // 销单事件
        if (!oldOrderStatus.equals(Order.ORDER_STATUS_YUPAIDAN)) {
            // web推送
            OrderCancelEvent cancelEvent = new OrderCancelEvent(order, driver, oldDriverStatus,
                oldOrderStatus,
                "admin");
            applicationEventMulticaster.multicastEvent(cancelEvent);
        } else {
            // web推送
            OrderCancelYupaiEvent cancelYupaiEvent = new OrderCancelYupaiEvent(order, driver,
                oldDriverStatus,
                oldOrderStatus);
            applicationEventMulticaster.multicastEvent(cancelYupaiEvent);
        }

        chartYearService.addDayRecord(order);

        // 取消自动派单定时
        try {
            Timer timer = ThreadControl.TaskMaps.get("task_" + order.getId());
            if (null != timer) {
                timer.cancel();
                ThreadControl.TaskMaps.remove("task_" + order.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void driverCancel(Order order, String content) {

        Long driverid = order.getDriverId();
        Driver driver = driverMapper.selectByPrimaryKey(driverid);

        // 更新订单为销单
        order.setStatus(Order.ORDER_STATUS_CANCELED);
        order.setDriverId(null);
        order.setDriverName(null);
        order.setDriverRealName(null);
        order.setDriverPhone(null);
        order.setArrivePlaceDate(null);
        order.setStartDriveDate(null);
        orderMapper.updateByPrimaryKey(order);

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.xiaodan);
        os.setContent("服务人员【" + driver.getRealname() + "】取消了该订单");
        os.setMemo(content);
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        Integer oldDriverStatus = driver.getStatus();
        // 更新服务人员为空闲
        if (oldDriverStatus != Driver.DRIVER_OFFLINE) {
            driverMapper
                .updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null, driver.getId());
            driver.setStatus(Driver.DRIVER_ONLINE);
        }

        // 销单退款
        if (null != order.getPrePayTypeDetail() && !order.getPrePayTypeDetail()
            .equals(PayTypeDetails.coupon)) {
            Result<Passenger> result_p = passengerApi
                .findOnePassenger(order.getClientId(), settingUtils.get());
            Passenger passenger = result_p.getResult();
            if (null != passenger) {
                BigDecimal coupon_hasPayed = BigDecimal.ZERO;
                if (null != order.getCouponId()) {
                    Coupon coupon = salesApi.findOneCoupon(order.getCouponId()).getResult();
                    if (null != coupon) {
                        if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DEDUCTION)) {
//                            coupon_hasPayed = coupon.getCouponRule().getMoney();
                            coupon_hasPayed = coupon.getCouponPrice();
                        } else if (coupon.getCouponRule().getType()
                            .equals(CouponRule.TYPE_DISCOUNT)) {
//                            Double discount = coupon.getCouponRule().getDiscount();
                            Double discount = coupon.getCouponDiscount();
                            coupon_hasPayed = order.getShouldCash()
                                .multiply(new BigDecimal(1)
                                    .subtract(new BigDecimal(discount).divide(new BigDecimal(10))))
                                .setScale(0, BigDecimal.ROUND_DOWN);
                        }
                    }
                }
                BigDecimal tuikuan = order.getShouldCash().subtract(coupon_hasPayed);
                if (tuikuan.doubleValue() > 0) {
                    if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                        passengerApi.createPassengerAccount(passenger, null, tuikuan,
                            PassengerAccount.PayType.RECHARGE_TYPE_CANCEL_RETURN,
                            PassengerAccount.OPERATING_SYS,
                            "销单退款:" + content, order.getId(), order.getOrderNumber(),
                            PassengerAccount.ORDER_TYPE_DAIJIA, null, true, false,
                            settingUtils.get());
                    } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                        Enterprise enterprise = passengerApi
                            .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                            .getResult();
                        if (null != enterprise) {
                            passengerApi.createEnterpriseAccount(enterprise, tuikuan,
                                PassengerAccount.PayType.RECHARGE_TYPE_CANCEL_RETURN,
                                PassengerAccount.OPERATING_SYS, "销单退款:" + content, order.getId(),
                                order.getOrderNumber(), PassengerAccount.ORDER_TYPE_DAIJIA, null,
                                true, false,
                                settingUtils.get());
                        }
                    }
                }

            }
        }

        // 强制销单事件
        ReactorVo rVo = new ReactorVo();
        rVo.setOrder(order);
        rVo.setDriver(driver);
        rVo.setOldDriverStatus(oldDriverStatus);
        OrderPowerCancelEvent powerCancelEvent = new OrderPowerCancelEvent(rVo);
        applicationEventMulticaster.multicastEvent(powerCancelEvent);

        chartYearService.addDayRecord(order);

        // 取消自动派单定时
        try {
            Timer timer = ThreadControl.TaskMaps.get("task_" + order.getId());
            if (null != timer) {
                timer.cancel();
                ThreadControl.TaskMaps.remove("task_" + order.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void powercancel(Order order, String content) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Long driverid = order.getDriverId();

        // 更新订单为销单
        order.setStatus(Order.ORDER_STATUS_CANCELED);
        order.setDriverId(null);
        order.setDriverName(null);
        order.setDriverRealName(null);
        order.setDriverPhone(null);
        order.setArrivePlaceDate(null);
        order.setStartDriveDate(null);
        orderMapper.updateByPrimaryKey(order);

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.xiaodan);
        os.setContent("【" + principal.getUsername() + "】强制取消了该订单");
        os.setMemo(content);
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        final Driver driver = driverMapper.selectByPrimaryKey(driverid);
        Integer oldDriverStatus = null;
        if (null != driver) {
            // 更新服务人员为空闲
            oldDriverStatus = driver.getStatus();
            if (oldDriverStatus != Driver.DRIVER_OFFLINE) {
                driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null,
                    driver.getId());
                driver.setStatus(Driver.DRIVER_ONLINE);
            }

        }

        // 销单退款
        if (null != order.getPrePayTypeDetail() && !order.getPrePayTypeDetail()
            .equals(PayTypeDetails.coupon)) {
            Result<Passenger> result_p = passengerApi
                .findOnePassenger(order.getClientId(), settingUtils.get());
            Passenger passenger = result_p.getResult();
            if (null != passenger) {
                BigDecimal coupon_hasPayed = BigDecimal.ZERO;
                if (null != order.getCouponId()) {
                    Coupon coupon = salesApi.findOneCoupon(order.getCouponId()).getResult();
                    if (null != coupon) {
                        if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DEDUCTION)) {
//                            coupon_hasPayed = coupon.getCouponRule().getMoney();
                            coupon_hasPayed = coupon.getCouponPrice();
                        } else if (coupon.getCouponRule().getType()
                            .equals(CouponRule.TYPE_DISCOUNT)) {
//                            Double discount = coupon.getCouponRule().getDiscount();
                            Double discount = coupon.getCouponDiscount();
                            coupon_hasPayed = order.getShouldCash()
                                .multiply(new BigDecimal(1)
                                    .subtract(new BigDecimal(discount).divide(new BigDecimal(10))))
                                .setScale(0, BigDecimal.ROUND_DOWN);
                        }
                    }
                }
                BigDecimal tuikuan = order.getShouldCash().subtract(coupon_hasPayed);
                if (tuikuan.doubleValue() > 0) {
                    if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                        passengerApi.createPassengerAccount(passenger, null, tuikuan,
                            PassengerAccount.PayType.RECHARGE_TYPE_CANCEL_RETURN,
                            PassengerAccount.OPERATING_SYS,
                            "销单退款:" + content, order.getId(), order.getOrderNumber(),
                            PassengerAccount.ORDER_TYPE_DAIJIA, null, true, false,
                            settingUtils.get());
                    } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                        Enterprise enterprise = passengerApi
                            .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                            .getResult();
                        if (null != enterprise) {
                            passengerApi.createEnterpriseAccount(enterprise, tuikuan,
                                PassengerAccount.PayType.RECHARGE_TYPE_CANCEL_RETURN,
                                PassengerAccount.OPERATING_SYS, "销单退款:" + content, order.getId(),
                                order.getOrderNumber(), PassengerAccount.ORDER_TYPE_DAIJIA, null,
                                true, false,
                                settingUtils.get());
                        }
                    }
                }

            }
        }

        // 强制销单事件
        ReactorVo rVo = new ReactorVo();
        rVo.setOrder(order);
        rVo.setDriver(driver);
        rVo.setOldDriverStatus(oldDriverStatus);
        OrderPowerCancelEvent powerCancelEvent = new OrderPowerCancelEvent(rVo);
        applicationEventMulticaster.multicastEvent(powerCancelEvent);

        chartYearService.addDayRecord(order);

        // 取消自动派单定时
        try {
            Timer timer = ThreadControl.TaskMaps.get("task_" + order.getId());
            if (null != timer) {
                timer.cancel();
                ThreadControl.TaskMaps.remove("task_" + order.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void customerCancel(Order order, String content) {

        Integer oldOrderStatus = order.getStatus();
        Long driverid = order.getDriverId();

        // 更新订单为销单
        order.setStatus(Order.ORDER_STATUS_CANCELED);
        order.setDriverId(null);
        order.setDriverName(null);
        order.setDriverRealName(null);
        order.setDriverPhone(null);
        order.setArrivePlaceDate(null);
        order.setStartDriveDate(null);
        orderMapper.updateByPrimaryKey(order);

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.xiaodan);
        os.setContent("客户取消了该订单：");
        os.setMemo(content);
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        Driver tmpd = null;
        if (null != driverid) {
            tmpd = driverMapper.selectByPrimaryKey(driverid);
        }

        Driver driver = tmpd;
        Integer oldDriverStatus = null;
        if (null != driver) {
            oldDriverStatus = driver.getStatus();
        }

        if (null != driver) {
            // 更新服务人员为空闲
            if (oldDriverStatus != Driver.DRIVER_OFFLINE) {
                driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null,
                    driver.getId());
                driver.setStatus(Driver.DRIVER_ONLINE);
            }
        }

        // 销单退款
        if (null != order.getPrePayTypeDetail() && !order.getPrePayTypeDetail()
            .equals(PayTypeDetails.coupon)) {
            Result<Passenger> result_p = passengerApi
                .findOnePassenger(order.getClientId(), settingUtils.get());
            Passenger passenger = result_p.getResult();
            if (null != passenger) {
                BigDecimal coupon_hasPayed = BigDecimal.ZERO;
                if (null != order.getCouponId()) {
                    Coupon coupon = salesApi.findOneCoupon(order.getCouponId()).getResult();
                    if (null != coupon) {
                        if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DEDUCTION)) {
//                            coupon_hasPayed = coupon.getCouponRule().getMoney();
                            coupon_hasPayed = coupon.getCouponPrice();
                        } else if (coupon.getCouponRule().getType()
                            .equals(CouponRule.TYPE_DISCOUNT)) {
//                            Double discount = coupon.getCouponRule().getDiscount();
                            Double discount = coupon.getCouponDiscount();
                            coupon_hasPayed = order.getShouldCash()
                                .multiply(new BigDecimal(1)
                                    .subtract(new BigDecimal(discount).divide(new BigDecimal(10))))
                                .setScale(0, BigDecimal.ROUND_DOWN);
                        }
                    }
                }
                BigDecimal tuikuan = order.getShouldCash().subtract(coupon_hasPayed);
                if (tuikuan.doubleValue() > 0) {
                    if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                        passengerApi.createPassengerAccount(passenger, null, tuikuan,
                            PassengerAccount.PayType.RECHARGE_TYPE_CANCEL_RETURN,
                            PassengerAccount.OPERATING_SYS,
                            "销单退款:" + content, order.getId(), order.getOrderNumber(),
                            PassengerAccount.ORDER_TYPE_DAIJIA, null, true, false,
                            settingUtils.get());
                    } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                        Enterprise enterprise = passengerApi
                            .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                            .getResult();
                        if (null != enterprise) {
                            passengerApi.createEnterpriseAccount(enterprise, tuikuan,
                                PassengerAccount.PayType.RECHARGE_TYPE_CANCEL_RETURN,
                                PassengerAccount.OPERATING_SYS, "销单退款:" + content, order.getId(),
                                order.getOrderNumber(), PassengerAccount.ORDER_TYPE_DAIJIA, null,
                                true, false,
                                settingUtils.get());
                        }
                    }
                }

            }
        }

        // 醉无忧 - 人保新加
        if (null != order.getOrderNoRenBao() && null != order.getCuponNoRenBao()) {
            zWYApi.syncOrderInfo(order.getOrderNoRenBao(), order.getCuponNoRenBao(),
                order.getOrderNumber(),
                String.valueOf(6), order.getClientPhone());
        }

        if (oldOrderStatus.equals(Order.ORDER_STATUS_NEW) || oldOrderStatus
            .equals(Order.ORDER_STATUS_YIPAIDAN)) {
            // 销单事件
            OrderCancelEvent cancelEvent = new OrderCancelEvent(order, driver, oldDriverStatus,
                oldOrderStatus,
                "customerCancel");
            applicationEventMulticaster.multicastEvent(cancelEvent);
        } else if (oldOrderStatus.equals(Order.ORDER_STATUS_BUSY)) {
            // 强制销单事件
            ReactorVo rVo = new ReactorVo();
            rVo.setOrder(order);
            rVo.setDriver(driver);
            rVo.setOldDriverStatus(oldDriverStatus);
            OrderPowerCancelEvent powerCancelEvent = new OrderPowerCancelEvent(rVo);
            applicationEventMulticaster.multicastEvent(powerCancelEvent);
        }

        chartYearService.addDayRecord(order);

        // 取消自动派单定时
        try {
            Timer timer = ThreadControl.TaskMaps.get("task_" + order.getId());
            if (null != timer) {
                timer.cancel();
                ThreadControl.TaskMaps.remove("task_" + order.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void managerCancel(Order order, String content) {

        Integer oldOrderStatus = order.getStatus();
        Long driverid = order.getDriverId();

        // 更新订单为销单
        order.setStatus(Order.ORDER_STATUS_CANCELED);
        order.setDriverId(null);
        order.setDriverName(null);
        order.setDriverRealName(null);
        order.setDriverPhone(null);
        order.setArrivePlaceDate(null);
        order.setStartDriveDate(null);
        orderMapper.updateByPrimaryKey(order);

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.xiaodan);
        os.setContent("客户经理取消了该订单：");
        os.setMemo(content);
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        Driver tmpd = null;
        if (null != driverid) {
            tmpd = driverMapper.selectByPrimaryKey(driverid);
        }

        Driver driver = tmpd;
        Integer oldDriverStatus = null;
        if (null != driver) {
            oldDriverStatus = driver.getStatus();
        }

        if (null != driver) {
            // 更新服务人员为空闲
            if (oldDriverStatus != Driver.DRIVER_OFFLINE) {
                driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null,
                    driver.getId());
                driver.setStatus(Driver.DRIVER_ONLINE);
            }
        }

        // 销单退款
        if (null != order.getPrePayTypeDetail() && !order.getPrePayTypeDetail()
            .equals(PayTypeDetails.coupon)) {
            Result<Passenger> result_p = passengerApi
                .findOnePassenger(order.getClientId(), settingUtils.get());
            Passenger passenger = result_p.getResult();
            if (null != passenger) {
                BigDecimal coupon_hasPayed = BigDecimal.ZERO;
                if (null != order.getCouponId()) {
                    Coupon coupon = salesApi.findOneCoupon(order.getCouponId()).getResult();
                    if (null != coupon) {
                        if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DEDUCTION)) {
                            coupon_hasPayed = coupon.getCouponRule().getMoney();
                        } else if (coupon.getCouponRule().getType()
                            .equals(CouponRule.TYPE_DISCOUNT)) {
                            Double discount = coupon.getCouponRule().getDiscount();
                            coupon_hasPayed = order.getShouldCash()
                                .multiply(new BigDecimal(1)
                                    .subtract(new BigDecimal(discount).divide(new BigDecimal(10))))
                                .setScale(0, BigDecimal.ROUND_DOWN);
                        }
                    }
                }
                BigDecimal tuikuan = order.getShouldCash().subtract(coupon_hasPayed);
                if (tuikuan.doubleValue() > 0) {
                    if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                        passengerApi.createPassengerAccount(passenger, null, tuikuan,
                            PassengerAccount.PayType.RECHARGE_TYPE_CANCEL_RETURN,
                            PassengerAccount.OPERATING_SYS,
                            "销单退款:" + content, order.getId(), order.getOrderNumber(),
                            PassengerAccount.ORDER_TYPE_DAIJIA, null, true, false,
                            settingUtils.get());
                    } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                        Enterprise enterprise = passengerApi
                            .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                            .getResult();
                        if (null != enterprise) {
                            passengerApi.createEnterpriseAccount(enterprise, tuikuan,
                                PassengerAccount.PayType.RECHARGE_TYPE_CANCEL_RETURN,
                                PassengerAccount.OPERATING_SYS, "销单退款:" + content, order.getId(),
                                order.getOrderNumber(), PassengerAccount.ORDER_TYPE_DAIJIA, null,
                                true, false,
                                settingUtils.get());
                        }
                    }
                }

            }
        }

        if (oldOrderStatus.equals(Order.ORDER_STATUS_NEW) || oldOrderStatus
            .equals(Order.ORDER_STATUS_YIPAIDAN)) {
            // 销单事件
            OrderCancelEvent cancelEvent = new OrderCancelEvent(order, driver, oldDriverStatus,
                oldOrderStatus,
                "managerCancel");
            applicationEventMulticaster.multicastEvent(cancelEvent);
        } else if (oldOrderStatus.equals(Order.ORDER_STATUS_BUSY)) {
            // 强制销单事件
            ReactorVo rVo = new ReactorVo();
            rVo.setOrder(order);
            rVo.setDriver(driver);
            rVo.setOldDriverStatus(oldDriverStatus);
            OrderPowerCancelEvent powerCancelEvent = new OrderPowerCancelEvent(rVo);
            applicationEventMulticaster.multicastEvent(powerCancelEvent);
        }

        chartYearService.addDayRecord(order);

        // 取消自动派单定时
        try {
            Timer timer = ThreadControl.TaskMaps.get("task_" + order.getId());
            if (null != timer) {
                timer.cancel();
                ThreadControl.TaskMaps.remove("task_" + order.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void revoke(Order order, String content) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Long driverid = order.getDriverId();

        int oldOrderStatus = order.getStatus();

        // 更新订单为新订单
        order.setStatus(Order.ORDER_STATUS_NEW);
        order.setDriverId(null);
        order.setDriverName(null);
        order.setDriverRealName(null);
        order.setDriverPhone(null);
        order.setArrivePlaceDate(null);
        order.setStartDriveDate(null);
        orderMapper.updateByPrimaryKey(order);

        // 更新服务人员为空闲
        Driver driver = driverMapper.selectByPrimaryKey(driverid);
        Integer oldDriverStatus = null;
        if (oldOrderStatus != Order.ORDER_STATUS_YUPAIDAN && null != driver) {
            oldDriverStatus = driver.getStatus();
            // 更新服务人员为空闲
            if (oldDriverStatus != Driver.DRIVER_OFFLINE) {
                driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null,
                    driver.getId());
                driver.setStatus(Driver.DRIVER_ONLINE);
            }
        }

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.revoke);
        if (null != principal) {
            os.setContent("【" + principal.getUsername() + "】收回了该订单");
            os.setMemo(content);
        } else {
            os.setContent(content);
        }
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        // 订单收回事件
        if (oldOrderStatus != Order.ORDER_STATUS_YUPAIDAN) {
            ReactorVo rVo = new ReactorVo();
            rVo.setOrder(order);
            rVo.setDriver(driver);
            rVo.setOldDriverStatus(oldDriverStatus);
            OrderRevokeEvent revokeEvent = new OrderRevokeEvent(rVo);
            applicationEventMulticaster.multicastEvent(revokeEvent);
        } else {
            ReactorVo rVo = new ReactorVo();
            rVo.setOrder(order);
            rVo.setDriver(driver);
            rVo.setOldDriverStatus(oldDriverStatus);
            OrderRevokelYupaiEvent revokeYupaidanEvent = new OrderRevokelYupaiEvent(rVo);
            applicationEventMulticaster.multicastEvent(revokeYupaidanEvent);
        }

        // 拒绝工单记录
        OrderRefuseRecord refuseRecord = new OrderRefuseRecord();
        refuseRecord.setDriverId(driver.getId());
        refuseRecord.setOrderId(order.getId());
        orderRefuseRecordMapper.insertRecord(refuseRecord);

        // 自动派单定时器
        if (ThreadControl.SysAutoRunning) {
            Setting setting = settingUtils.get();

            Timer timer = new Timer();
            OrderTimerTask orderTimerTask = new OrderTimerTask(setting.getAutoPaidanKm1(),
                setting.getAutoPaidanTime1(),
                setting.getAutoPaidanKm2(), setting.getAutoPaidanTime2(),
                setting.getAutoPaidanKm3(),
                setting.getAutoPaidanTime3(), applicationEventMulticaster, order.getId(),
                order.getClientLatitude(),
                order.getClientLongitude(), 1);
            timer.schedule(orderTimerTask, setting.getAutoPaidanTime1() * 1000);
            ThreadControl.TaskMaps.put("task_" + order.getId(), timer);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void powerrevoke(Order order, String content) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Long driverid = order.getDriverId();

        // 更新订单为新订单
        order.setStatus(Order.ORDER_STATUS_NEW);
        order.setDriverId(null);
        order.setDriverName(null);
        order.setDriverRealName(null);
        order.setDriverPhone(null);
        order.setArrivePlaceDate(null);
        order.setStartDriveDate(null);
        orderMapper.updateByPrimaryKey(order);

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.revoke);
        os.setContent("【" + principal.getUsername() + "】强制收回了该订单");
        os.setMemo(content);
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        Driver driver = driverMapper.selectByPrimaryKey(driverid);

        Integer oldDriverStatus = null;
        if (null != driver) {
            // 更新服务人员为空闲
            oldDriverStatus = driver.getStatus();
            if (oldDriverStatus != Driver.DRIVER_OFFLINE) {
                driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null,
                    driver.getId());
                driver.setStatus(Driver.DRIVER_ONLINE);
            }
        }

        // 强制收回事件
        ReactorVo rVo = new ReactorVo();
        rVo.setOrder(order);
        rVo.setDriver(driver);
        rVo.setOldDriverStatus(oldDriverStatus);
        OrderPowerRevokeEvent powerRevokeEvent = new OrderPowerRevokeEvent(rVo);
        applicationEventMulticaster.multicastEvent(powerRevokeEvent);

        // 自动派单定时器
        if (ThreadControl.SysAutoRunning) {
            Setting setting = settingUtils.get();

            Timer timer = new Timer();
            OrderTimerTask orderTimerTask = new OrderTimerTask(setting.getAutoPaidanKm1(),
                setting.getAutoPaidanTime1(),
                setting.getAutoPaidanKm2(), setting.getAutoPaidanTime2(),
                setting.getAutoPaidanKm3(),
                setting.getAutoPaidanTime3(), applicationEventMulticaster, order.getId(),
                order.getClientLatitude(),
                order.getClientLongitude(), 1);
            timer.schedule(orderTimerTask, setting.getAutoPaidanTime1() * 1000);
            ThreadControl.TaskMaps.put("task_" + order.getId(), timer);
        }

    }

    @Override
    public Result<Order> autoCallback(Order order, Driver driver) {

        Result<Order> result = new Result<Order>();
        result.setSuccess(false);

        // 更新订单为新订单
        order.setStatus(Order.ORDER_STATUS_NEW);
        order.setDriverId(null);
        order.setDriverName(null);
        order.setDriverRealName(null);
        order.setDriverPhone(null);
        order.setArrivePlaceDate(null);
        order.setStartDriveDate(null);
        orderMapper.updateByPrimaryKey(order);

        // 更新服务人员为空闲
        Integer oldDriverStatus = driver.getStatus();

        // 更新服务人员为空闲
        if (oldDriverStatus != Driver.DRIVER_OFFLINE) {
            driverMapper
                .updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null, driver.getId());
            driver.setStatus(Driver.DRIVER_ONLINE);
        }

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.revoke);
        os.setContent("时间逾期，系统自动收回了该订单");
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        // 订单收回事件
        ReactorVo rVo = new ReactorVo();
        rVo.setOrder(order);
        rVo.setDriver(driver);
        rVo.setOldDriverStatus(oldDriverStatus);
        OrderRevokeEvent revokeEvent = new OrderRevokeEvent(rVo);
        applicationEventMulticaster.multicastEvent(revokeEvent);

        // 拒绝工单记录
        OrderRefuseRecord refuseRecord = new OrderRefuseRecord();
        refuseRecord.setDriverId(driver.getId());
        refuseRecord.setOrderId(order.getId());
        orderRefuseRecordMapper.insertRecord(refuseRecord);

        // 自动派单定时器
        if (ThreadControl.SysAutoRunning) {
            Setting setting = settingUtils.get();

            Timer timer = new Timer();
            OrderTimerTask orderTimerTask = new OrderTimerTask(setting.getAutoPaidanKm1(),
                setting.getAutoPaidanTime1(),
                setting.getAutoPaidanKm2(), setting.getAutoPaidanTime2(),
                setting.getAutoPaidanKm3(),
                setting.getAutoPaidanTime3(), applicationEventMulticaster, order.getId(),
                order.getClientLatitude(),
                order.getClientLongitude(), 1);
            timer.schedule(orderTimerTask, setting.getAutoPaidanTime1() * 1000);
            ThreadControl.TaskMaps.put("task_" + order.getId(), timer);
        }

        result.setSuccess(true);
        return result;
    }

    @Override
    public boolean IsThereAnSameOrder(String OrderNumber) {
        Integer i = orderMapper.CountByOrderNumber(OrderNumber);
        if (i.intValue() >= 2) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refuse(Order order, String content) {

        Long driverid = order.getDriverId();

        // 更新订单为新订单
        order.setStatus(Order.ORDER_STATUS_NEW);
        order.setDriverId(null);
        order.setDriverName(null);
        order.setDriverRealName(null);
        order.setDriverPhone(null);
        order.setRefused(true);
        order.setArrivePlaceDate(null);
        order.setStartDriveDate(null);
        orderMapper.updateByPrimaryKey(order);

        // 更新服务人员为空闲
        Driver driver = driverMapper.selectByPrimaryKey(driverid);
        Integer oldDriverStatus = null;
        if (null != driver) {
            oldDriverStatus = driver.getStatus();
            if (oldDriverStatus != Driver.DRIVER_OFFLINE) {
                driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null,
                    driver.getId());
                driver.setStatus(Driver.DRIVER_ONLINE);
            }
        }

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.refuse);
        os.setContent("【" + driver.getRealname() + "（" + driver.getPhone() + "）】拒绝了工单");
        os.setMemo(content);
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        // 拒绝工单记录
        OrderRefuseRecord refuseRecord = new OrderRefuseRecord();
        refuseRecord.setDriverId(driver.getId());
        refuseRecord.setOrderId(order.getId());
        orderRefuseRecordMapper.insertRecord(refuseRecord);

        // 拒绝工单记录
        DriverRefuseRecord driverRefuseRecord = new DriverRefuseRecord();
        driverRefuseRecord.setEmployId(driver.getId());
        driverRefuseRecord.setEmployRealName(driver.getRealname());
        driverRefuseRecord.setEmployUserName(driver.getUsername());
        driverRefuseRecord.setEmployPhone(driver.getPhone());
        driverRefuseRecord.setHappend(new Date());
        driverRefuseRecord.setOrderId(order.getId());
        driverRefuseRecord.setOrderNumber(order.getOrderNumber());
        driverRefuseRecord.setOrderCompanyId(order.getCompanyId());
        driverRefuseRecord.setMemo(content);
        driverRefuseRecord.setOrderType(DriverRefuseRecord.OrderType.daijia);
        driverRefuseRecordMapper.insertRecord(driverRefuseRecord);

        // 拒绝工单事件
        ReactorVo rVo = new ReactorVo();
        rVo.setOrder(order);
        rVo.setDriver(driver);
        rVo.setOldDriverStatus(oldDriverStatus);
        OrderRefuseEvent refuseEvent = new OrderRefuseEvent(rVo);
        applicationEventMulticaster.multicastEvent(refuseEvent);

        // 自动派单定时器
        if (ThreadControl.SysAutoRunning) {
            Setting setting = settingUtils.get();

            Timer timer = new Timer();
            OrderTimerTask orderTimerTask = new OrderTimerTask(setting.getAutoPaidanKm1(),
                setting.getAutoPaidanTime1(),
                setting.getAutoPaidanKm2(), setting.getAutoPaidanTime2(),
                setting.getAutoPaidanKm3(),
                setting.getAutoPaidanTime3(), applicationEventMulticaster, order.getId(),
                order.getClientLatitude(),
                order.getClientLongitude(), 1);
            timer.schedule(orderTimerTask, setting.getAutoPaidanTime1() * 1000);
            ThreadControl.TaskMaps.put("task_" + order.getId(), timer);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int accept(Order order, Driver driver) {

        order.setStatus(Order.ORDER_STATUS_BUSY);
        orderMapper.updateByPrimaryKey(order);

        if (null != order.getOrderGroupId()) {
            OrderGroup orderGroup = orderGroupMapper.selectByPrimaryKey(order.getOrderGroupId());
            if (null != orderGroup && null == orderGroup.getDriverId()) {
                orderGroup.setDriverId(driver.getId());
                orderGroupMapper.updateByPrimaryKey(orderGroup);
            }
        }

        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.accept);
        os.setContent("【" + order.getDriverRealName() + "】接受订单");
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        // 服务人员为忙碌
        driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_BUSY,
            Driver.DRIVER_JOBSTATUS_DAIJIA,
            driver.getId());
        driver.setStatus(Driver.DRIVER_BUSY);

        // 服务人员扣费
        Company company = companyMapper.selectByPrimaryKey(order.getCompanyId());

        if (null != company.getInfoFeeType()
            && company.getInfoFeeType().compareTo(Company.InfoFeeType.acceptTask) == 0) {
            if (company.getInfoFee().doubleValue() != 0) {
                driver.setVirtual(driver.getVirtual().subtract(company.getInfoFee()));
                driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                // 扣费记录
                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                driverPaymentsRecord.setMoney(company.getInfoFee());
                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                driverPaymentsRecord.setInfoFeeType(DriverPaymentsRecord.INFOFEE_TYPE_INFO);
                driverPaymentsRecord.setDriverId(driver.getId());
                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                driverPaymentsRecord.setOrderId(order.getId());
                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                driverPaymentsRecord.setMemo("扣除公司所得信息费" + company.getInfoFee() + "元。");
                driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                driverPaymentsRecord.setHappend(new Date());
                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                // 财务记录（保险费/信息费）
                Company mainCompany = companyMapper.selectMainCompany();
                DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb_f = new StringBuilder();
                sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 保险费/信息费
                sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                sb_f.append(format_f.format(new Date()));// 年月日时间
                sb_f.append(
                    OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                financialRecord.setCode(sb_f.toString());
                financialRecord.setCompanyId(mainCompany.getId());
                financialRecord.setCompanyName(mainCompany.getAbbreviation());
                financialRecord.setOrderCompanyId(mainCompany.getId());
                financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                financialRecord
                    .setMemo("订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                        + order.getOrderNumber() + "</a>】信息费");
                financialRecord.setMoney(company.getInfoFee());
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                financialRecord.setWho(driver.getRealname());
                financialRecord.setOrderId(order.getId());
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                financialRecordMapper.insertRecord(financialRecord);
            }
            // 代驾险
            if (null != order.getDjxFee() && order.getDjxFee().doubleValue() != 0) {
                driver.setVirtual(driver.getVirtual().subtract(order.getDjxFee()));
                driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                // 扣费记录
                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                driverPaymentsRecord.setMoney(order.getDjxFee());
                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                driverPaymentsRecord.setInfoFeeType(DriverPaymentsRecord.INFOFEE_TYPE_DJX);
                driverPaymentsRecord.setDriverId(driver.getId());
                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                driverPaymentsRecord.setOrderId(order.getId());
                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                driverPaymentsRecord.setMemo("扣除公司所得代驾险" + order.getDjxFee() + "元。");
                driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                driverPaymentsRecord.setHappend(new Date());
                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                // 财务记录（保险费）
                Company mainCompany = companyMapper.selectMainCompany();
                DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb_f = new StringBuilder();
                sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 保险费
                sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                sb_f.append(format_f.format(new Date()));// 年月日时间
                sb_f.append(
                    OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                financialRecord.setCode(sb_f.toString());
                financialRecord.setCompanyId(mainCompany.getId());
                financialRecord.setCompanyName(mainCompany.getAbbreviation());
                financialRecord.setOrderCompanyId(mainCompany.getId());
                financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                financialRecord
                    .setMemo("订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                        + order.getOrderNumber() + "</a>】代驾险");
                financialRecord.setMoney(order.getDjxFee());
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                financialRecord.setWho(driver.getRealname());
                financialRecord.setOrderId(order.getId());
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                financialRecordMapper.insertRecord(financialRecord);

                // 保险记录
                DjInsurance djInsurance = new DjInsurance();
                djInsurance.setInsuranceType(DjInsurance.InsuranceType.djx);
                djInsurance.setMoney(order.getDjxFee());
                djInsurance.setOrderId(order.getId());
                djInsurance.setOrderNo(order.getOrderNumber());
                djInsuranceMapper.insertRecord(djInsurance);

                DjxNoticeEvent djxNoticeEvent = new DjxNoticeEvent(driver, djInsurance);
                applicationEventMulticaster.multicastEvent(djxNoticeEvent);
            }
            // 意外险
            if (null != order.getYwxFee() && order.getYwxFee().doubleValue() != 0) {
                driver.setVirtual(driver.getVirtual().subtract(order.getYwxFee()));
                driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                // 扣费记录
                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                driverPaymentsRecord.setMoney(order.getYwxFee());
                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                driverPaymentsRecord.setInfoFeeType(DriverPaymentsRecord.INFOFEE_TYPE_YWX);
                driverPaymentsRecord.setDriverId(driver.getId());
                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                driverPaymentsRecord.setOrderId(order.getId());
                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                driverPaymentsRecord.setMemo("扣除公司所得意外险" + order.getYwxFee() + "元。");
                driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                driverPaymentsRecord.setHappend(new Date());
                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                // 财务记录（保险费）
                Company mainCompany = companyMapper.selectMainCompany();
                DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb_f = new StringBuilder();
                sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 保险费
                sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                sb_f.append(format_f.format(new Date()));// 年月日时间
                sb_f.append(
                    OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                financialRecord.setCode(sb_f.toString());
                financialRecord.setCompanyId(mainCompany.getId());
                financialRecord.setCompanyName(mainCompany.getAbbreviation());
                financialRecord.setOrderCompanyId(mainCompany.getId());
                financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                financialRecord
                    .setMemo("订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                        + order.getOrderNumber() + "</a>】意外险");
                financialRecord.setMoney(order.getYwxFee());
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                financialRecord.setWho(driver.getRealname());
                financialRecord.setOrderId(order.getId());
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                financialRecordMapper.insertRecord(financialRecord);

                // 保险记录
                DjInsurance djInsurance = new DjInsurance();
                djInsurance.setInsuranceType(DjInsurance.InsuranceType.ywx);
                djInsurance.setMoney(order.getYwxFee());
                djInsurance.setOrderId(order.getId());
                djInsurance.setOrderNo(order.getOrderNumber());
                djInsuranceMapper.insertRecord(djInsurance);

                YwxNoticeEvent ywxNoticeEvent = new YwxNoticeEvent(driver, djInsurance);
                applicationEventMulticaster.multicastEvent(ywxNoticeEvent);
            }
        }

        return 0;
    }

    @Override
    public List<Order> findByDriverAndFinishTime(Long driverId, Date begin, Date end) {

        return orderMapper.selectFinishedByDriverWithDate(driverId, begin, end, null, null);

    }

    @Override
    public long counByDriverAndFinishTime(Long driverId, Date start, Date end) {

        return orderMapper.countFinishedByDriverWithDate(driverId, start, end);
    }

    @Override
    public double sumByDriverAndFinishTime(Long driverId, Date start, Date end) {

        BigDecimal money = orderMapper.sumMoneyByDriverWithDate(driverId, start, end);
        if (null == money) {
            return 0d;
        }
        return money.doubleValue();

    }

    @Override
    public Page<Order> findByDriverAndFinishTime(Long driverId, Date start, Date end, Integer page,
        Integer limit) {

        Pageable pageable = new PageRequest(page, limit);

        List<Order> content = orderMapper
            .selectFinishedByDriverWithDate(driverId, start, end, page * limit, limit);
        long total = orderMapper.countFinishedByDriverWithDate(driverId, start, end);
        return new PageImpl<Order>(content, pageable, total);

    }

    @Override
    public long counByDriver(Long driverId) {

        return orderMapper.countFinishedByDriverWithDate(driverId, null, null);
    }

    @Override
    public double sumByDriver(Long driverId) {
        BigDecimal money = orderMapper.sumMoneyByDriverWithDate(driverId, null, null);
        if (null == money) {
            return 0d;
        }
        return money.doubleValue();
    }

    @Override
    public Page<Order> findByDriver(final Long driverId, Integer page, Integer limit) {

        Pageable pageable = new PageRequest(page, limit);

        List<Order> content = orderMapper
            .selectFinishedByDriverWithDate(driverId, null, null, page * limit, limit);
        long total = orderMapper.countFinishedByDriverWithDate(driverId, null, null);
        return new PageImpl<Order>(content, pageable, total);

    }

    @Transactional(rollbackFor = Exception.class)
    public Order completeTaskV3(Order order, Date waitDate, Date travelDate, Long couponId) {

        Driver driver = driverMapper.selectByPrimaryKey(order.getDriverId());

        String place = "";

        if (null != driver) {
            try {
                place = HttpClientUtil
                    .getPlaceByLngAndLat(driver.getLongitude(), driver.getLatitude());
                order.setToPlaceLongitude(driver.getLongitude());
                order.setToPlaceLatitude(driver.getLatitude());
                order.setToPlace(place);
            } catch (Exception e) {
                logger.debug(e.getMessage());
            }
        }

        order.setOrderStatuss(orderStatusMapper.selectByOrder(order.getId()));

        chartYearService.addDayRecord(order);// 增加统计

        if (null == order.getDaokehuTime()) {
            OrderStatus os = new OrderStatus();
            os.setOrderId(order.getId());
            os.setStatusType(StatusType.daokehu);
            os.setContent("【" + order.getDriverRealName() + "】到达客户所在地，开始等待");
            os.setHappened(waitDate);
            orderStatusMapper.insertRecord(os);
        }

        if (null == order.getDaijiaTime()) {
            OrderStatus os = new OrderStatus();
            os = new OrderStatus();
            os.setOrderId(order.getId());
            os.setStatusType(StatusType.daijia);

            // 中途等待
            // Date
            // start=order.getDaokehuTime()==null?waitDate:order.getDaokehuTime();
            Date start = waitDate;
            Date end = travelDate;
            long time = end.getTime() - start.getTime();

            Integer zhongtu = 0;
            zhongtu = (int) (order.getWaitedTime() - (time / (1000 * 60)));
            if (zhongtu < 0) {
                zhongtu = 0;
            }

            order.setWaitedZtTime(zhongtu);

            os.setContent(
                "【" + order.getDriverRealName() + "】出发前往客户目的地，等待总时间为：" + order.getWaitedTime()
                    + "分钟（中途等待："
                    + zhongtu + "分钟）");

            os.setHappened(travelDate);
            orderStatusMapper.insertRecord(os);
        }

        OrderStatus os = new OrderStatus();
        os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.wancheng);
        os.setContent(
            "【" + order.getDriverRealName() + "】到达目的地，并且结算完成，行程时间为：" + order.getTravelTime()
                + "分钟,行驶里程为："
                + order.getMileage() + "公里");
        os.setHappened(order.getFinishTime());
        orderStatusMapper.insertRecord(os);

        // 更新订单
        orderMapper.updateByPrimaryKey(order);

        // 订单财务记录
        OrderFinishedInfo orderFinishedInfo = new OrderFinishedInfo();
        orderFinishedInfo.setOrderId(order.getId());
        orderFinishedInfo.setOrderNumber(order.getOrderNumber());
        orderFinishedInfo.setFinishTime(order.getFinishTime());
        orderFinishedInfo.setCreateTime(order.getCreated());
        orderFinishedInfo.setClientId(order.getClientId());
        orderFinishedInfo.setClientPhone(order.getClientPhone());
        orderFinishedInfo.setDriverId(order.getDriverId());
        orderFinishedInfo.setCompanyId(order.getCompanyId());
        orderFinishedInfo.setPayTypeDetails(order.getPayTypeDetails());
        orderFinishedInfo.setShouldCash(order.getShouldCash());
        orderFinishedInfo.setRealCash(order.getRealCash());
        orderFinishedInfo.setCouponMoney(order.getCouponMoney());
        orderFinishedInfo.setCashMoney(order.getCashMoney());
        orderFinishedInfo.setSignMoney(order.getSignMoney());
        orderFinishedInfo.setBalanceMoney(order.getBalanceMoney());
        // 信息费,可能是接单产生
        List<DriverPaymentsRecord> infoFeeList = driverPaymentsRecordMapper
            .selectByRecordTypeAndOrder(
                DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI, order.getId(),
                DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
        if (!CollectionUtils.isEmpty(infoFeeList)) {
            for (DriverPaymentsRecord driverPaymentsRecord : infoFeeList) {
                if (driverPaymentsRecord.getInfoFeeType()
                    .equals(DriverPaymentsRecord.INFOFEE_TYPE_INFO)) {
                    orderFinishedInfo.setInfoFee(
                        orderFinishedInfo.getInfoFee().add(driverPaymentsRecord.getMoney()));
                } else if (driverPaymentsRecord.getInfoFeeType()
                    .equals(DriverPaymentsRecord.INFOFEE_TYPE_DJX)) {
                    orderFinishedInfo.setDjxFee(
                        orderFinishedInfo.getDjxFee().add(driverPaymentsRecord.getMoney()));
                } else if (driverPaymentsRecord.getInfoFeeType()
                    .equals(DriverPaymentsRecord.INFOFEE_TYPE_YWX)) {
                    orderFinishedInfo.setYwxFee(
                        orderFinishedInfo.getYwxFee().add(driverPaymentsRecord.getMoney()));
                }
            }
        }
        // 订单财务记录

        BigDecimal realCash = order.getRealCash();
        BigDecimal shouruMoney = order.getRealCash();
        String wxMemo = "";

        // 优惠劵是否参与提成
        Setting setting = settingUtils.get();
        boolean couponTicheng = setting.isCouponTicheng();

        // 是否使用了优惠劵
        Coupon coupon = null;
        BigDecimal couponRuleMoney = BigDecimal.ZERO;
        if (null != couponId) {
            coupon = salesApi.findOneCoupon(couponId).getResult();
        }
        if (null != coupon) {
            CouponRule couponRule = coupon.getCouponRule();
            if (null != couponRule) {
                couponRuleMoney = couponRule.getMoney();
            }

            if (!couponTicheng) {
                realCash = realCash.subtract(couponRuleMoney);
                if (realCash.compareTo(BigDecimal.ZERO) == -1) {
                    realCash = BigDecimal.ZERO;
                }
            }
            shouruMoney = shouruMoney.subtract(couponRuleMoney);
            if (shouruMoney.compareTo(BigDecimal.ZERO) == -1) {
                shouruMoney = BigDecimal.ZERO;
            }
        }

        // 客户经理提成
        WeixinManagerXOrder wxo = weixinManagerXOrderMapper.selectByOrderId(order.getId());
        BigDecimal wxMoney = BigDecimal.ZERO;// 客户经理提成金额
        if (null != wxo) {
            wxo.setFinishedTime(order.getFinishTime());
            WeixinManager weixinManager = weixinManagerMapper
                .selectByPrimaryKey(wxo.getManagerId());
            if (null != weixinManager) {
                BigDecimal money = BigDecimal.ZERO;
                if (weixinManager.getWeixinManagerMoneyType()
                    .equals(WeixinManagerMoneyType.guding)) {
                    if (realCash.compareTo(weixinManager.getFixedMoney()) == -1) {
                        money = realCash;
                        wxo.setMoney(money);
                    } else {
                        money = weixinManager.getFixedMoney();
                        wxo.setMoney(money);
                    }
                } else if (weixinManager.getWeixinManagerMoneyType()
                    .equals(WeixinManagerMoneyType.bili)) {
                    money = realCash.multiply(weixinManager.getRatioMoney())
                        .divide(new BigDecimal(100));
                    wxo.setMoney(money);
                }
                weixinManager.setVirtual(weixinManager.getVirtual().add(money));
                weixinManagerMapper.updateByPrimaryKey(weixinManager);
                wxMoney = money;
                realCash = realCash.subtract(money);
                shouruMoney = shouruMoney.subtract(money);
                wxMemo = "（客户经理经理提成" + money + "元）";

                // 代收客户经理
                Company weixinManagerCompany = companyMapper
                    .selectByPrimaryKey(weixinManager.getCompanyId());
                Company orderCompany = companyMapper.selectByPrimaryKey(order.getCompanyId());

                DateFormat format = new SimpleDateFormat("yyyyMMdd");
                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb = new StringBuilder();
                sb.append(OrderNumberConfig.FINANCIAL_MANAGERTIXIAN);// 客户经理提成金额
                sb.append(OrderNumberConfig.FINANCIAL_WHO_MANAGER);// 对象 客户经理
                sb.append(format.format(new Date()));// 年月日时间
                sb.append(
                    OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                financialRecord.setCode(sb.toString());
                financialRecord.setCompanyId(weixinManagerCompany.getId());
                financialRecord.setCompanyName(weixinManagerCompany.getAbbreviation());
                financialRecord.setOrderCompanyId(orderCompany.getId());
                financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                financialRecord.setMemo("代收客户经理【" + weixinManager.getName() + "】" + money + "元");
                financialRecord.setMoney(money);
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                financialRecord.setWho(weixinManager.getName());
                financialRecord.setOrderId(order.getId());
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_MANAGERDAISHOU);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                financialRecordMapper.insertRecord(financialRecord);

            }
            weixinManagerXOrderMapper.updateByPrimaryKey(wxo);
        }

        // 订单财务记录
        orderFinishedInfo.setWxManagerMoney(wxMoney);
        // 订单财务记录

        // 服务人员设为空闲
        if (null != driver) {
            driver.setStatus(Driver.DRIVER_ONLINE);
            driver.setTodayOrders(driver.getTodayOrders() + 1);
            driver.setMonthOrders(driver.getMonthOrders() + 1);
            driver.setDriveTimes(driver.getDriveTimes() + 1);
            driverMapper.updateWhenFinishOrderByKey(driver);

            // 扣费 提成
            if (null != driver.getType() && Driver.DRIVER_TYPR_PARTTIME.equals(driver.getType())) {

                DriverChoseLevel driverChoseLevel = null;
                DriverChoseLevelCar driverChoseLevelCar = null;
                driverChoseLevel = driverChoseLevelMapper.selectByDriverAndCompany(driver.getId(),
                    order.getCompanyId());

                if (null != driverChoseLevel || null != driverChoseLevelCar) {

                    DriverLevel driverLevel = null;
                    if (null != driverChoseLevel) {
                        if (driverChoseLevel.getDriverlevelId() == 0) {// 始终使用本公司提成
                            DriverChoseLevel driverChoseLevel2 = driverChoseLevelMapper
                                .selectByDriverAndCompany(driver.getId(), driver.getCompanyId());
                            if (null != driverChoseLevel2) {
                                driverLevel = driverLevelMapper
                                    .selectByPrimaryKey(driverChoseLevel2.getDriverlevelId());
                            }
                        } else {
                            driverLevel = driverLevelMapper
                                .selectByPrimaryKey(driverChoseLevel.getDriverlevelId());
                        }
                    } else if (null != driverChoseLevelCar) {
                        if (driverChoseLevelCar.getDriverlevelId() == 0) {// 始终使用本公司提成
                            DriverChoseLevelCar driverChoseLevelCar2 = driverChoseLevelCarMapper
                                .selectByDriverAndCompany(driver.getId(), driver.getCompanyId());
                            if (null != driverChoseLevelCar2) {
                                driverLevel = driverLevelMapper
                                    .selectByPrimaryKey(driverChoseLevelCar2.getDriverlevelId());
                            }
                        } else {
                            driverLevel = driverLevelMapper
                                .selectByPrimaryKey(driverChoseLevelCar.getDriverlevelId());
                        }
                    }

                    DriverLevelDetail detail = null;
                    DriverLevelMoneyTimeDetail moneyTimeDetail = null;

                    if (null != driverLevel) {
                        if (driverLevel.getType().equals(0)) {
                            driverLevel.setDriverLevelDetails(
                                driverLevelDetailMapper.selectByDriverLevel(driverLevel.getId()));
                            if (driverLevel.getTimePoint().equals(TimePoint.serviceTime)) {
                                detail = driverLevel.getDeatil(order.getServerTime());
                            } else if (driverLevel.getTimePoint().equals(TimePoint.startDrive)) {
                                detail = driverLevel.getDeatil(travelDate);
                            } else if (driverLevel.getTimePoint().equals(TimePoint.finishTime)) {
                                detail = driverLevel.getDeatil(order.getFinishTime());
                            }
                        } else if (driverLevel.getType().equals(1)) {
                            driverLevel.setDriverLevelMoneyTimeDetails(
                                driverLevelMoneyTimeDetailMapper
                                    .selectByDriverLevel(driverLevel.getId()));
                            if (driverLevel.getTimePoint().equals(TimePoint.serviceTime)) {
                                moneyTimeDetail = driverLevel
                                    .getMoneyTimeDeatil(order.getServerTime());
                            } else if (driverLevel.getTimePoint().equals(TimePoint.startDrive)) {
                                moneyTimeDetail = driverLevel.getMoneyTimeDeatil(travelDate);
                            } else if (driverLevel.getTimePoint().equals(TimePoint.finishTime)) {
                                moneyTimeDetail = driverLevel
                                    .getMoneyTimeDeatil(order.getFinishTime());
                            }
                        }
                    }

                    if (null != detail) {

                        if (null != coupon && couponTicheng) {
                            if (couponRuleMoney.compareTo(order.getRealCash()) != -1
                                || order.getPayTypeDetails().equals(PayTypeDetails.coupon_sign)
                                || order.getPayTypeDetails()
                                .equals(PayTypeDetails.coupon_balance)) {

                                BigDecimal money = BigDecimal.ZERO;

                                StringBuilder sbmemo = new StringBuilder();
                                sbmemo.append(
                                    "订单【" + order.getOrderNumber() + "】，客户【" + order.getClientName()
                                        + "("
                                        + order.getClientPhone() + ")】，");

                                if (order.getPayTypeDetails().equals(PayTypeDetails.coupon_sign)) {
                                    sbmemo.append("优惠劵+签单支付，");
                                } else if (order.getPayTypeDetails()
                                    .equals(PayTypeDetails.coupon_balance)) {
                                    sbmemo.append("优惠劵+余额支付，");
                                }

                                if (detail.getDriverLevelType().equals(DriverLevelType.ticheng)) {
                                    if (order.getRealCash().compareTo(detail.getMinCommission())
                                        == -1) {
                                        money = realCash.subtract(detail.getLowCommission());
                                        sbmemo.append("按照【低于" + detail.getMinCommission() + "元公司得"
                                            + detail.getLowCommission() + "元】方式，服务人员得" + money
                                            + "元。");
                                    } else {
                                        money = realCash.multiply(
                                            new BigDecimal(100).subtract(detail.getCommission()))
                                            .divide(new BigDecimal(100));
                                        sbmemo.append("按照【" + detail.getCommission()
                                            + "%公司所得】提成方式，返提成给服务人员。");
                                    }
                                } else if (detail.getDriverLevelType()
                                    .equals(DriverLevelType.guding)) {
                                    if (order.getRealCash().compareTo(detail.getMinMoney()) == -1) {
                                        money = realCash.subtract(detail.getLowMoney());
                                        sbmemo.append(
                                            "按照【低于" + detail.getMinMoney() + "元公司得" + detail
                                                .getLowMoney()
                                                + "元】方式，服务人员得" + money + "元。");
                                    } else {

                                        sbmemo.append(
                                            "按照【" + detail.getMoney() + "元公司所得】提成方式，返提成给服务人员。");

                                        if (realCash.compareTo(detail.getMoney()) == -1) {
                                            money = BigDecimal.ZERO;
                                        } else {
                                            money = realCash.subtract(detail.getMoney());
                                        }

                                    }
                                }

                                sbmemo.append("客户使用了面值" + couponRuleMoney + "元的优惠劵，");
                                sbmemo.append("优惠劵参与提成计算");

                                driver.setVirtual(driver.getVirtual().add(money));
                                driverMapper
                                    .updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                driverPaymentsRecord.setMoney(money);
                                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                driverPaymentsRecord
                                    .setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                                driverPaymentsRecord.setDriverId(driver.getId());
                                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                                driverPaymentsRecord.setOrderId(order.getId());
                                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                                driverPaymentsRecord
                                    .setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                                driverPaymentsRecord.setMemo(sbmemo.toString() + wxMemo);
                                driverPaymentsRecord
                                    .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                driverPaymentsRecord
                                    .setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                                driverPaymentsRecord.setHappend(new Date());
                                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                                // 订单财务记录
                                orderFinishedInfo.setDriverMoney(driverPaymentsRecord.getMoney());
                                if (order.getPayTypeDetails().equals(PayTypeDetails.coupon_sign)) {
                                    orderFinishedInfo.setCompanyMoney(
                                        order.getSignMoney()
                                            .subtract(orderFinishedInfo.getDriverMoney())
                                            .subtract(orderFinishedInfo.getWxManagerMoney()));
                                } else if (order.getPayTypeDetails()
                                    .equals(PayTypeDetails.coupon_balance)) {
                                    orderFinishedInfo.setCompanyMoney(
                                        order.getBalanceMoney()
                                            .subtract(orderFinishedInfo.getDriverMoney())
                                            .subtract(orderFinishedInfo.getWxManagerMoney()));
                                }
                                // 订单财务记录

                            } else if (order.getPayTypeDetails()
                                .equals(PayTypeDetails.coupon_cash)) {
                                BigDecimal money = BigDecimal.ZERO;// 公司所得金额

                                StringBuilder sbmemo = new StringBuilder();

                                if (detail.getDriverLevelType().equals(DriverLevelType.ticheng)) {

                                    if (order.getRealCash().compareTo(detail.getMinCommission())
                                        == -1) {// 公司不提成
                                        money = detail.getLowCommission();
                                        sbmemo.append(
                                            "按照【低于" + detail.getMinCommission() + "元公司得" + detail
                                                .getLowCommission()
                                                + "元】方式，公司得" + detail.getLowCommission() + "元");
                                    } else {
                                        money = realCash.multiply(detail.getCommission())
                                            .divide(new BigDecimal(100));
                                        sbmemo.append("按照【" + detail.getCommission()
                                            + "%公司所得】提成方式，扣除公司所得提成。");
                                    }

                                } else if (detail.getDriverLevelType()
                                    .equals(DriverLevelType.guding)) {

                                    if (order.getRealCash().compareTo(detail.getMinMoney())
                                        == -1) {// 公司不提成
                                        money = detail.getLowMoney();
                                        sbmemo.append(
                                            "按照【低于" + detail.getMinMoney() + "元公司得" + detail
                                                .getLowMoney()
                                                + "元】方式，公司得" + detail.getLowMoney() + "元");
                                    } else {
                                        sbmemo.append(
                                            "按照【" + detail.getMoney() + "元公司所得】提成方式，扣除公司所得提成。");

                                        if (realCash.compareTo(detail.getMoney()) == -1) {
                                            money = realCash;
                                        } else {
                                            money = detail.getMoney();
                                        }
                                    }
                                }

                                sbmemo.append("客户使用了面值" + couponRuleMoney + "元的优惠劵，");
                                sbmemo.append("优惠劵参与提成计算");

                                BigDecimal xianjin = order.getCashMoney();// 服务人员现有现金
                                BigDecimal yingde = realCash.subtract(money);// 服务人员应得提成
                                if (yingde.compareTo(BigDecimal.ZERO) == -1) {
                                    yingde = BigDecimal.ZERO;
                                }

                                if (xianjin.compareTo(yingde) == -1) {// 加钱
                                    driver.setVirtual(
                                        driver.getVirtual().add(yingde.subtract(xianjin)));
                                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(),
                                        driver.getId());

                                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                    driverPaymentsRecord.setMoney(yingde.subtract(xianjin));
                                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                    driverPaymentsRecord
                                        .setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                                    driverPaymentsRecord.setDriverId(driver.getId());
                                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                                    driverPaymentsRecord.setOrderId(order.getId());
                                    driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                                    driverPaymentsRecord
                                        .setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                                    driverPaymentsRecord.setMemo(sbmemo.toString() + wxMemo);
                                    driverPaymentsRecord
                                        .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                    driverPaymentsRecord
                                        .setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                                    driverPaymentsRecord.setHappend(new Date());
                                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                                    // 订单财务记录
                                    orderFinishedInfo
                                        .setDriverMoney(driverPaymentsRecord.getMoney()
                                            .add(order.getCashMoney()));
                                    orderFinishedInfo.setCompanyMoney(
                                        order.getCashMoney()
                                            .subtract(orderFinishedInfo.getDriverMoney())
                                            .subtract(orderFinishedInfo.getWxManagerMoney()));
                                    // 订单财务记录
                                } else {// 减钱
                                    driver.setVirtual(
                                        driver.getVirtual().subtract(xianjin.subtract(yingde)));
                                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(),
                                        driver.getId());

                                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                    driverPaymentsRecord.setMoney(xianjin.subtract(yingde));
                                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                    driverPaymentsRecord
                                        .setRecordType(DriverPaymentsRecord.CONSUMED_TYPE_ORDER);
                                    driverPaymentsRecord.setDriverId(driver.getId());
                                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                                    driverPaymentsRecord.setOrderId(order.getId());
                                    driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                                    driverPaymentsRecord
                                        .setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                                    driverPaymentsRecord.setMemo(sbmemo.toString() + wxMemo);
                                    driverPaymentsRecord
                                        .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                    driverPaymentsRecord
                                        .setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                                    driverPaymentsRecord.setHappend(new Date());
                                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                                    // 订单财务记录
                                    orderFinishedInfo.setDriverMoney(realCash.subtract(money));
                                    orderFinishedInfo.setCompanyMoney(
                                        order.getCashMoney()
                                            .subtract(orderFinishedInfo.getDriverMoney())
                                            .subtract(orderFinishedInfo.getWxManagerMoney()));
                                    // 订单财务记录
                                }

                            }
                        } else {// .....

                            if (order.getPayType().compareTo(PayType.cash) == 0) {// 现金

                                // if((detail.getDriverLevelType().equals(DriverLevelType.ticheng)
                                // &&
                                // order.getRealCash().compareTo(detail.getMinCommission())!=-1)
                                // ||
                                // (detail.getDriverLevelType().equals(DriverLevelType.guding)
                                // && order.getRealCash().compareTo(detail.getMinMoney())!=-1)){

                                BigDecimal money = BigDecimal.ZERO;// 公司所得金额

                                StringBuilder sbmemo = new StringBuilder();

                                if (detail.getDriverLevelType().equals(DriverLevelType.ticheng)) {

                                    if (order.getRealCash().compareTo(detail.getMinCommission())
                                        == -1) {// 公司不提成
                                        money = detail.getLowCommission();
                                        sbmemo.append(
                                            "按照【低于" + detail.getMinCommission() + "元公司得" + detail
                                                .getLowCommission()
                                                + "元】方式，公司得" + detail.getLowCommission() + "元");
                                    } else {
                                        money = realCash.multiply(detail.getCommission())
                                            .divide(new BigDecimal(100));
                                        sbmemo.append("按照【" + detail.getCommission()
                                            + "%公司所得】提成方式，扣除公司所得提成。");
                                    }

                                } else if (detail.getDriverLevelType()
                                    .equals(DriverLevelType.guding)) {

                                    if (order.getRealCash().compareTo(detail.getMinMoney())
                                        == -1) {// 公司不提成
                                        money = detail.getLowMoney();
                                        sbmemo.append(
                                            "按照【低于" + detail.getMinMoney() + "元公司得" + detail
                                                .getLowMoney()
                                                + "元】方式，公司得" + detail.getLowMoney() + "元");
                                    } else {
                                        sbmemo.append(
                                            "按照【" + detail.getMoney() + "元公司所得】提成方式，扣除公司所得提成。");

                                        if (realCash.compareTo(detail.getMoney()) == -1) {
                                            money = realCash;
                                        } else {
                                            money = detail.getMoney();
                                        }
                                    }

                                }

                                if (null != coupon) {
                                    sbmemo.append("客户使用了面值" + couponRuleMoney + "元的优惠劵，");
                                    if (couponTicheng) {
                                        sbmemo.append("优惠劵参与提成计算");
                                    } else {
                                        sbmemo.append("优惠劵不参与提成计算");
                                    }
                                }

                                driver.setVirtual(driver.getVirtual().subtract(money));

                                if (wxMoney.compareTo(BigDecimal.ZERO) == 1) {// 现金支付 多减去客户经理的钱
                                    driver.setVirtual(driver.getVirtual().subtract(wxMoney));
                                    money = money.add(wxMoney);
                                }
                                driverMapper
                                    .updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                                // 扣费记录
                                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                driverPaymentsRecord.setMoney(money);
                                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                driverPaymentsRecord
                                    .setRecordType(DriverPaymentsRecord.CONSUMED_TYPE_ORDER);
                                driverPaymentsRecord.setDriverId(driver.getId());
                                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                                driverPaymentsRecord.setOrderId(order.getId());
                                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                                driverPaymentsRecord
                                    .setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                                driverPaymentsRecord.setMemo(sbmemo.toString() + wxMemo);
                                driverPaymentsRecord
                                    .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                driverPaymentsRecord
                                    .setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                                driverPaymentsRecord.setHappend(new Date());
                                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                                // 订单财务记录
                                orderFinishedInfo
                                    .setDriverMoney(realCash.subtract(money).add(wxMoney));
                                orderFinishedInfo.setCompanyMoney(
                                    order.getCashMoney()
                                        .subtract(orderFinishedInfo.getDriverMoney())
                                        .subtract(orderFinishedInfo.getWxManagerMoney()));
                                // 订单财务记录
                                // }

                            } else if (order.getPayType().compareTo(PayType.sign) == 0) {// 签单
                                BigDecimal money = BigDecimal.ZERO;

                                StringBuilder sbmemo = new StringBuilder();
                                sbmemo.append(
                                    "订单【" + order.getOrderNumber() + "】，客户【" + order.getClientName()
                                        + "("
                                        + order.getClientPhone() + ")】，");

                                sbmemo.append("签单支付，");

                                if (detail.getDriverLevelType().equals(DriverLevelType.ticheng)) {
                                    if (order.getRealCash().compareTo(detail.getMinCommission())
                                        == -1) {
                                        money = realCash.subtract(detail.getLowCommission());
                                        sbmemo.append("按照【低于" + detail.getMinCommission() + "元公司得"
                                            + detail.getLowCommission() + "元】方式，服务人员得" + money
                                            + "元。");
                                    } else {
                                        money = realCash.multiply(
                                            new BigDecimal(100).subtract(detail.getCommission()))
                                            .divide(new BigDecimal(100));
                                        sbmemo.append("按照【" + detail.getCommission()
                                            + "%公司所得】提成方式，返提成给服务人员。");
                                    }
                                } else if (detail.getDriverLevelType()
                                    .equals(DriverLevelType.guding)) {
                                    if (order.getRealCash().compareTo(detail.getMinMoney()) == -1) {
                                        money = realCash.subtract(detail.getLowMoney());
                                        sbmemo.append(
                                            "按照【低于" + detail.getMinMoney() + "元公司得" + detail
                                                .getLowMoney()
                                                + "元】方式，服务人员得" + money + "元。");
                                    } else {

                                        sbmemo.append(
                                            "按照【" + detail.getMoney() + "元公司所得】提成方式，返提成给服务人员。");

                                        if (realCash.compareTo(detail.getMoney()) == -1) {
                                            money = BigDecimal.ZERO;
                                        } else {
                                            money = realCash.subtract(detail.getMoney());
                                        }

                                    }
                                }

                                if (null != coupon) {
                                    sbmemo.append("客户使用了面值" + couponRuleMoney + "元的优惠劵，");
                                    if (couponTicheng) {
                                        sbmemo.append("优惠劵参与提成计算");
                                    } else {
                                        sbmemo.append("优惠劵不参与提成计算");
                                    }
                                }

                                driver.setVirtual(driver.getVirtual().add(money));
                                driverMapper
                                    .updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                driverPaymentsRecord.setMoney(money);
                                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                driverPaymentsRecord
                                    .setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                                driverPaymentsRecord.setDriverId(driver.getId());
                                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                                driverPaymentsRecord.setOrderId(order.getId());
                                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                                driverPaymentsRecord
                                    .setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                                driverPaymentsRecord.setMemo(sbmemo.toString() + wxMemo);
                                driverPaymentsRecord
                                    .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                driverPaymentsRecord
                                    .setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                                driverPaymentsRecord.setHappend(new Date());
                                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                                // 订单财务记录
                                orderFinishedInfo.setDriverMoney(driverPaymentsRecord.getMoney());
                                orderFinishedInfo.setCompanyMoney(
                                    order.getSignMoney()
                                        .subtract(orderFinishedInfo.getDriverMoney())
                                        .subtract(orderFinishedInfo.getWxManagerMoney()));
                                // 订单财务记录

                            } else if (order.getPayType().compareTo(PayType.balance) == 0) {// 余额

                                if (order.getPayTypeDetails()
                                    .equals(PayTypeDetails.balance_cash)) {// 余额+现金
                                    BigDecimal balanceMoney = order.getBalanceMoney();
                                    BigDecimal cashMoney = order.getCashMoney();
                                    BigDecimal totalMoney = order.getRealCash();

                                    StringBuilder sbmemo = new StringBuilder();
                                    sbmemo.append("订单【" + order.getOrderNumber() + "】，客户【" + order
                                        .getClientName() + "("
                                        + order.getClientPhone() + ")】，");
                                    sbmemo.append("余额(" + order.getBalanceMoney() + "元)+现金(" + order
                                        .getCashMoney()
                                        + "元)支付。");

                                    if (detail.getDriverLevelType()
                                        .equals(DriverLevelType.ticheng)) {// 比例提成

                                        totalMoney = totalMoney.subtract(wxMoney);
                                        if (totalMoney.doubleValue() < 0) {
                                            totalMoney = BigDecimal.ZERO;
                                        }

                                        BigDecimal driverFashengMoney = BigDecimal.ZERO;// 服务人员余额应该增加或减少的钱
                                        BigDecimal money = BigDecimal.ZERO;// 公司所得金额

                                        if (order.getRealCash().compareTo(detail.getMinCommission())
                                            == -1) {// 公司不提成
                                            money = detail.getLowCommission();
                                        } else {
                                            money = totalMoney.multiply(detail.getCommission())
                                                .divide(new BigDecimal(100));
                                        }

                                        boolean jiaOrjian = true;// true加钱 false减钱
                                        if ((money.add(wxMoney)).doubleValue() <= balanceMoney
                                            .doubleValue()) {
                                            driverFashengMoney = balanceMoney
                                                .subtract((money.add(wxMoney)));
                                            jiaOrjian = true;
                                        } else {
                                            driverFashengMoney = (money.add(wxMoney))
                                                .subtract(balanceMoney);
                                            jiaOrjian = false;
                                        }

                                        if (jiaOrjian) {// 如果发生金额大于0 给服务人员加钱

                                            driver.setVirtual(
                                                driver.getVirtual().add(driverFashengMoney));
                                            driverMapper
                                                .updateVirtualByPrimaryKey(driver.getVirtual(),
                                                    driver.getId());

                                            DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                            driverPaymentsRecord.setMoney(driverFashengMoney);
                                            driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                            driverPaymentsRecord
                                                .setRecordType(
                                                    DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                                            driverPaymentsRecord.setDriverId(driver.getId());
                                            driverPaymentsRecord
                                                .setDriverRealName(driver.getRealname());
                                            driverPaymentsRecord
                                                .setDriverUserName(driver.getUsername());
                                            driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                            driverPaymentsRecord
                                                .setDriverCompanyId(driver.getCompanyId());
                                            driverPaymentsRecord.setOrderId(order.getId());
                                            driverPaymentsRecord
                                                .setOrderNumber(order.getOrderNumber());
                                            driverPaymentsRecord.setOrderType(
                                                DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                            driverPaymentsRecord
                                                .setOrderCompanyId(order.getCompanyId());
                                            driverPaymentsRecord
                                                .setMemo(sbmemo.toString() + wxMemo);
                                            driverPaymentsRecord
                                                .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                            driverPaymentsRecord
                                                .setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                                            driverPaymentsRecord.setHappend(new Date());
                                            driverPaymentsRecordMapper
                                                .insertRecord(driverPaymentsRecord);

                                            // 订单财务记录
                                            orderFinishedInfo.setDriverMoney(
                                                order.getCashMoney()
                                                    .add(driverPaymentsRecord.getMoney()));
                                            orderFinishedInfo.setCompanyMoney(money);
                                            // 订单财务记录
                                        } else {
                                            driver.setVirtual(
                                                driver.getVirtual().subtract(driverFashengMoney));
                                            driverMapper
                                                .updateVirtualByPrimaryKey(driver.getVirtual(),
                                                    driver.getId());
                                            // 扣费记录
                                            DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                            driverPaymentsRecord.setMoney(driverFashengMoney);
                                            driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                            driverPaymentsRecord
                                                .setRecordType(
                                                    DriverPaymentsRecord.CONSUMED_TYPE_ORDER);
                                            driverPaymentsRecord.setDriverId(driver.getId());
                                            driverPaymentsRecord
                                                .setDriverRealName(driver.getRealname());
                                            driverPaymentsRecord
                                                .setDriverUserName(driver.getUsername());
                                            driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                            driverPaymentsRecord
                                                .setDriverCompanyId(driver.getCompanyId());
                                            driverPaymentsRecord.setOrderId(order.getId());
                                            driverPaymentsRecord
                                                .setOrderNumber(order.getOrderNumber());
                                            driverPaymentsRecord.setOrderType(
                                                DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                            driverPaymentsRecord
                                                .setOrderCompanyId(order.getCompanyId());
                                            driverPaymentsRecord
                                                .setMemo(sbmemo.toString() + wxMemo);
                                            driverPaymentsRecord
                                                .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                            driverPaymentsRecord
                                                .setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                                            driverPaymentsRecord.setHappend(new Date());
                                            driverPaymentsRecordMapper
                                                .insertRecord(driverPaymentsRecord);

                                            // 订单财务记录
                                            orderFinishedInfo.setDriverMoney(
                                                cashMoney.subtract(driverFashengMoney));
                                            orderFinishedInfo.setCompanyMoney(money);
                                            // 订单财务记录
                                        }

                                    } else if (detail.getDriverLevelType()
                                        .equals(DriverLevelType.guding)) {// 固定提成

                                        BigDecimal driverFashengMoney = BigDecimal.ZERO;// 服务人员余额应该增加或减少的钱

                                        BigDecimal money = BigDecimal.ZERO;// 公司所得金额
                                        if (order.getRealCash().compareTo(detail.getMinMoney())
                                            == -1) {// 公司不提成
                                            money = detail.getLowMoney();
                                        } else {
                                            money = detail.getMoney();
                                        }

                                        boolean jiaOrjian = true;// true加钱 false减钱
                                        if ((money.add(wxMoney)).doubleValue() <= balanceMoney
                                            .doubleValue()) {
                                            driverFashengMoney = balanceMoney
                                                .subtract((money.add(wxMoney)));
                                            jiaOrjian = true;
                                        } else {
                                            driverFashengMoney = (money.add(wxMoney))
                                                .subtract(balanceMoney);
                                            jiaOrjian = false;
                                        }

                                        if (jiaOrjian) {// 如果发生金额大于0 给服务人员加钱
                                            driver.setVirtual(
                                                driver.getVirtual().add(driverFashengMoney));
                                            driverMapper
                                                .updateVirtualByPrimaryKey(driver.getVirtual(),
                                                    driver.getId());

                                            DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                            driverPaymentsRecord.setMoney(driverFashengMoney);
                                            driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                            driverPaymentsRecord
                                                .setRecordType(
                                                    DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                                            driverPaymentsRecord.setDriverId(driver.getId());
                                            driverPaymentsRecord
                                                .setDriverRealName(driver.getRealname());
                                            driverPaymentsRecord
                                                .setDriverUserName(driver.getUsername());
                                            driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                            driverPaymentsRecord
                                                .setDriverCompanyId(driver.getCompanyId());
                                            driverPaymentsRecord.setOrderId(order.getId());
                                            driverPaymentsRecord
                                                .setOrderNumber(order.getOrderNumber());
                                            driverPaymentsRecord.setOrderType(
                                                DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                            driverPaymentsRecord
                                                .setOrderCompanyId(order.getCompanyId());
                                            driverPaymentsRecord
                                                .setMemo(sbmemo.toString() + wxMemo);
                                            driverPaymentsRecord
                                                .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                            driverPaymentsRecord
                                                .setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                                            driverPaymentsRecord.setHappend(new Date());
                                            driverPaymentsRecordMapper
                                                .insertRecord(driverPaymentsRecord);

                                            // 订单财务记录
                                            orderFinishedInfo.setDriverMoney(
                                                order.getCashMoney()
                                                    .add(driverPaymentsRecord.getMoney()));
                                            orderFinishedInfo.setCompanyMoney(money);
                                            // 订单财务记录
                                        } else {
                                            driver.setVirtual(
                                                driver.getVirtual().subtract(driverFashengMoney));
                                            driverMapper
                                                .updateVirtualByPrimaryKey(driver.getVirtual(),
                                                    driver.getId());
                                            // 扣费记录
                                            DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                            driverPaymentsRecord.setMoney(driverFashengMoney);
                                            driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                            driverPaymentsRecord
                                                .setRecordType(
                                                    DriverPaymentsRecord.CONSUMED_TYPE_ORDER);
                                            driverPaymentsRecord.setDriverId(driver.getId());
                                            driverPaymentsRecord
                                                .setDriverRealName(driver.getRealname());
                                            driverPaymentsRecord
                                                .setDriverUserName(driver.getUsername());
                                            driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                            driverPaymentsRecord
                                                .setDriverCompanyId(driver.getCompanyId());
                                            driverPaymentsRecord.setOrderId(order.getId());
                                            driverPaymentsRecord
                                                .setOrderNumber(order.getOrderNumber());
                                            driverPaymentsRecord.setOrderType(
                                                DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                            driverPaymentsRecord
                                                .setOrderCompanyId(order.getCompanyId());
                                            driverPaymentsRecord
                                                .setMemo(sbmemo.toString() + wxMemo);
                                            driverPaymentsRecord
                                                .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                            driverPaymentsRecord
                                                .setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                                            driverPaymentsRecord.setHappend(new Date());
                                            driverPaymentsRecordMapper
                                                .insertRecord(driverPaymentsRecord);

                                            // 订单财务记录
                                            orderFinishedInfo.setDriverMoney(
                                                cashMoney.subtract(driverFashengMoney));
                                            orderFinishedInfo.setCompanyMoney(money);
                                            // 订单财务记录
                                        }

                                    }
                                } else {
                                    BigDecimal money = BigDecimal.ZERO;

                                    StringBuilder sbmemo = new StringBuilder();
                                    sbmemo.append("订单【" + order.getOrderNumber() + "】，客户【" + order
                                        .getClientName() + "("
                                        + order.getClientPhone() + ")】，");

                                    sbmemo.append("余额支付，");

                                    if (detail.getDriverLevelType()
                                        .equals(DriverLevelType.ticheng)) {
                                        if (order.getRealCash().compareTo(detail.getMinCommission())
                                            == -1) {
                                            money = realCash.subtract(detail.getLowCommission());
                                            sbmemo
                                                .append("按照【低于" + detail.getMinCommission() + "元公司得"
                                                    + detail.getLowCommission() + "元】方式，服务人员得"
                                                    + money + "元。");
                                        } else {
                                            money = realCash
                                                .multiply(new BigDecimal(100)
                                                    .subtract(detail.getCommission()))
                                                .divide(new BigDecimal(100));
                                            sbmemo.append("按照【" + detail.getCommission()
                                                + "%公司所得】提成方式，返提成给服务人员。");
                                        }
                                    } else if (detail.getDriverLevelType()
                                        .equals(DriverLevelType.guding)) {
                                        if (order.getRealCash().compareTo(detail.getMinMoney())
                                            == -1) {
                                            money = realCash.subtract(detail.getLowMoney());
                                            sbmemo.append(
                                                "按照【低于" + detail.getMinMoney() + "元公司得" + detail
                                                    .getLowMoney()
                                                    + "】方式，服务人员得" + money + "元。");
                                        } else {

                                            sbmemo.append(
                                                "按照【" + detail.getMoney() + "元公司所得】提成方式，返提成给服务人员。");

                                            if (realCash.compareTo(detail.getMoney()) == -1) {
                                                money = BigDecimal.ZERO;
                                            } else {
                                                money = realCash.subtract(detail.getMoney());
                                            }

                                        }
                                    }

                                    if (null != coupon) {
                                        sbmemo.append("客户使用了面值" + couponRuleMoney + "元的优惠劵，");
                                        if (couponTicheng) {
                                            sbmemo.append("优惠劵参与提成计算");
                                        } else {
                                            sbmemo.append("优惠劵不参与提成计算");
                                        }
                                    }

                                    driver.setVirtual(driver.getVirtual().add(money));
                                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(),
                                        driver.getId());

                                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                    driverPaymentsRecord.setMoney(money);
                                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                    driverPaymentsRecord
                                        .setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                                    driverPaymentsRecord.setDriverId(driver.getId());
                                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                                    driverPaymentsRecord.setOrderId(order.getId());
                                    driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                                    driverPaymentsRecord
                                        .setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                                    driverPaymentsRecord.setMemo(sbmemo.toString() + wxMemo);
                                    driverPaymentsRecord
                                        .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                    driverPaymentsRecord
                                        .setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                                    driverPaymentsRecord.setHappend(new Date());
                                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                                    orderFinishedInfo
                                        .setDriverMoney(driverPaymentsRecord.getMoney());
                                    orderFinishedInfo.setCompanyMoney(
                                        order.getBalanceMoney()
                                            .subtract(orderFinishedInfo.getDriverMoney())
                                            .subtract(orderFinishedInfo.getWxManagerMoney()));
                                }

                            }
                        }

                    } else if (null != moneyTimeDetail) {// 复杂提成

                        if (null != coupon && couponTicheng) {
                            if (couponRuleMoney.compareTo(order.getRealCash()) != -1
                                || order.getPayTypeDetails().equals(PayTypeDetails.coupon_sign)
                                || order.getPayTypeDetails()
                                .equals(PayTypeDetails.coupon_balance)) {

                                BigDecimal money = BigDecimal.ZERO;
                                BigDecimal companyMoney = BigDecimal.ZERO;

                                StringBuilder sbmemo = new StringBuilder();
                                sbmemo.append(
                                    "订单【" + order.getOrderNumber() + "】，客户【" + order.getClientName()
                                        + "("
                                        + order.getClientPhone() + ")】，");

                                if (order.getPayTypeDetails().equals(PayTypeDetails.coupon_sign)) {
                                    sbmemo.append("优惠劵+签单支付，");
                                } else if (order.getPayTypeDetails()
                                    .equals(PayTypeDetails.coupon_balance)) {
                                    sbmemo.append("优惠劵+余额支付，");
                                }

                                if (!CollectionUtils
                                    .isEmpty(moneyTimeDetail.getDriverLevelMoneyDetails())) {

                                    for (DriverLevelMoneyDetail dlmd : moneyTimeDetail
                                        .getDriverLevelMoneyDetails()) {
                                        if (realCash.doubleValue() >= dlmd.getFromMoney()
                                            .doubleValue()) {

                                            BigDecimal _money = BigDecimal.ZERO;
                                            if (realCash.doubleValue() >= dlmd.getToMoney()
                                                .doubleValue()) {
                                                _money = dlmd.getToMoney()
                                                    .subtract(dlmd.getFromMoney());
                                            } else {
                                                _money = realCash.subtract(dlmd.getFromMoney());
                                            }

                                            if (dlmd.getDriverLevelMoneyType()
                                                .equals(DriverLevelMoneyType.guding)) {// 固定
                                                BigDecimal tcMoney = dlmd.getMoney()
                                                    .multiply(
                                                        new BigDecimal((int) (_money.doubleValue()
                                                            / dlmd.getMoneyUnit().doubleValue())));
                                                companyMoney = companyMoney.add(tcMoney);
                                            } else if (dlmd.getDriverLevelMoneyType()
                                                .equals(DriverLevelMoneyType.ticheng)) {// 比例
                                                BigDecimal tcMoney = _money
                                                    .multiply(dlmd.getCommission())
                                                    .divide(new BigDecimal(100));
                                                companyMoney = companyMoney.add(tcMoney);
                                            }
                                        }
                                    }
                                }

                                sbmemo.append("提成方式为金额区间提成，公司应提成" + companyMoney + "元。");

                                if (realCash.compareTo(companyMoney) == -1) {
                                    companyMoney = realCash;
                                    money = BigDecimal.ZERO;
                                    sbmemo.append("金额不足，公司实际提成" + companyMoney + "元。");
                                } else {
                                    money = realCash.subtract(companyMoney);
                                }

                                sbmemo.append("客户使用了面值" + couponRuleMoney + "元的优惠劵，");
                                sbmemo.append("优惠劵参与提成计算");

                                driver.setVirtual(driver.getVirtual().add(money));
                                driverMapper
                                    .updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                driverPaymentsRecord.setMoney(money);
                                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                driverPaymentsRecord
                                    .setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                                driverPaymentsRecord.setDriverId(driver.getId());
                                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                                driverPaymentsRecord.setOrderId(order.getId());
                                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                                driverPaymentsRecord
                                    .setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                                driverPaymentsRecord.setMemo(sbmemo.toString() + wxMemo);
                                driverPaymentsRecord
                                    .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                driverPaymentsRecord
                                    .setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                                driverPaymentsRecord.setHappend(new Date());
                                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                                // 订单财务记录
                                orderFinishedInfo.setDriverMoney(driverPaymentsRecord.getMoney());
                                if (order.getPayTypeDetails().equals(PayTypeDetails.coupon_sign)) {
                                    orderFinishedInfo.setCompanyMoney(
                                        order.getSignMoney()
                                            .subtract(orderFinishedInfo.getDriverMoney())
                                            .subtract(orderFinishedInfo.getWxManagerMoney()));
                                } else if (order.getPayTypeDetails()
                                    .equals(PayTypeDetails.coupon_balance)) {
                                    orderFinishedInfo.setCompanyMoney(
                                        order.getBalanceMoney()
                                            .subtract(orderFinishedInfo.getDriverMoney())
                                            .subtract(orderFinishedInfo.getWxManagerMoney()));
                                }
                                // 订单财务记录

                            } else if (order.getPayTypeDetails()
                                .equals(PayTypeDetails.coupon_cash)) {

                                BigDecimal money = BigDecimal.ZERO;
                                BigDecimal companyMoney = BigDecimal.ZERO;// 公司所得金额

                                StringBuilder sbmemo = new StringBuilder();
                                sbmemo.append("客户使用了面值" + couponRuleMoney + "元的优惠劵，");
                                sbmemo.append("优惠劵参与提成计算");

                                if (!CollectionUtils
                                    .isEmpty(moneyTimeDetail.getDriverLevelMoneyDetails())) {

                                    for (DriverLevelMoneyDetail dlmd : moneyTimeDetail
                                        .getDriverLevelMoneyDetails()) {
                                        if (realCash.doubleValue() >= dlmd.getFromMoney()
                                            .doubleValue()) {

                                            BigDecimal _money = BigDecimal.ZERO;
                                            if (realCash.doubleValue() >= dlmd.getToMoney()
                                                .doubleValue()) {
                                                _money = dlmd.getToMoney()
                                                    .subtract(dlmd.getFromMoney());
                                            } else {
                                                _money = realCash.subtract(dlmd.getFromMoney());
                                            }

                                            if (dlmd.getDriverLevelMoneyType()
                                                .equals(DriverLevelMoneyType.guding)) {// 固定
                                                BigDecimal tcMoney = dlmd.getMoney()
                                                    .multiply(
                                                        new BigDecimal((int) (_money.doubleValue()
                                                            / dlmd.getMoneyUnit().doubleValue())));
                                                companyMoney = companyMoney.add(tcMoney);
                                            } else if (dlmd.getDriverLevelMoneyType()
                                                .equals(DriverLevelMoneyType.ticheng)) {// 比例
                                                BigDecimal tcMoney = _money
                                                    .multiply(dlmd.getCommission())
                                                    .divide(new BigDecimal(100));
                                                companyMoney = companyMoney.add(tcMoney);
                                            }
                                        }
                                    }
                                }

                                if (realCash.compareTo(companyMoney) == -1) {
                                    companyMoney = realCash;
                                    money = BigDecimal.ZERO;
                                    sbmemo.append("金额不足，公司实际提成" + companyMoney + "元。");
                                } else {
                                    money = realCash.subtract(companyMoney);
                                }

                                BigDecimal xianjin = order.getCashMoney();// 服务人员现有现金
                                BigDecimal yingde = money;// 服务人员应得提成
                                if (yingde.compareTo(BigDecimal.ZERO) == -1) {
                                    yingde = BigDecimal.ZERO;
                                }

                                if (xianjin.compareTo(yingde) == -1) {// 加钱
                                    driver.setVirtual(
                                        driver.getVirtual().add(yingde.subtract(xianjin)));
                                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(),
                                        driver.getId());

                                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                    driverPaymentsRecord.setMoney(yingde.subtract(xianjin));
                                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                    driverPaymentsRecord
                                        .setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                                    driverPaymentsRecord.setDriverId(driver.getId());
                                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                                    driverPaymentsRecord.setOrderId(order.getId());
                                    driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                                    driverPaymentsRecord
                                        .setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                                    driverPaymentsRecord.setMemo(sbmemo.toString() + wxMemo);
                                    driverPaymentsRecord
                                        .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                    driverPaymentsRecord
                                        .setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                                    driverPaymentsRecord.setHappend(new Date());
                                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                                    // 订单财务记录
                                    orderFinishedInfo
                                        .setDriverMoney(driverPaymentsRecord.getMoney()
                                            .add(order.getCashMoney()));
                                    orderFinishedInfo.setCompanyMoney(
                                        order.getCashMoney()
                                            .subtract(orderFinishedInfo.getDriverMoney())
                                            .subtract(orderFinishedInfo.getWxManagerMoney()));
                                    // 订单财务记录
                                } else {// 减钱
                                    driver.setVirtual(
                                        driver.getVirtual().subtract(xianjin.subtract(yingde)));
                                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(),
                                        driver.getId());

                                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                    driverPaymentsRecord.setMoney(xianjin.subtract(yingde));
                                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                    driverPaymentsRecord
                                        .setRecordType(DriverPaymentsRecord.CONSUMED_TYPE_ORDER);
                                    driverPaymentsRecord.setDriverId(driver.getId());
                                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                                    driverPaymentsRecord.setOrderId(order.getId());
                                    driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                                    driverPaymentsRecord
                                        .setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                                    driverPaymentsRecord.setMemo(sbmemo.toString() + wxMemo);
                                    driverPaymentsRecord
                                        .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                    driverPaymentsRecord
                                        .setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                                    driverPaymentsRecord.setHappend(new Date());
                                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                                    // 订单财务记录
                                    orderFinishedInfo.setDriverMoney(money);
                                    orderFinishedInfo.setCompanyMoney(
                                        order.getCashMoney()
                                            .subtract(orderFinishedInfo.getDriverMoney())
                                            .subtract(orderFinishedInfo.getWxManagerMoney()));
                                    // 订单财务记录
                                }

                            }
                        } else {
                            if (order.getPayType().compareTo(PayType.cash) == 0) {// 现金

                                BigDecimal money = BigDecimal.ZERO;
                                BigDecimal companyMoney = BigDecimal.ZERO;// 公司所得金额

                                StringBuilder sbmemo = new StringBuilder();

                                if (!CollectionUtils
                                    .isEmpty(moneyTimeDetail.getDriverLevelMoneyDetails())) {

                                    for (DriverLevelMoneyDetail dlmd : moneyTimeDetail
                                        .getDriverLevelMoneyDetails()) {
                                        if (realCash.doubleValue() >= dlmd.getFromMoney()
                                            .doubleValue()) {

                                            BigDecimal _money = BigDecimal.ZERO;
                                            if (realCash.doubleValue() >= dlmd.getToMoney()
                                                .doubleValue()) {
                                                _money = dlmd.getToMoney()
                                                    .subtract(dlmd.getFromMoney());
                                            } else {
                                                _money = realCash.subtract(dlmd.getFromMoney());
                                            }

                                            if (dlmd.getDriverLevelMoneyType()
                                                .equals(DriverLevelMoneyType.guding)) {// 固定
                                                BigDecimal tcMoney = dlmd.getMoney()
                                                    .multiply(
                                                        new BigDecimal((int) (_money.doubleValue()
                                                            / dlmd.getMoneyUnit().doubleValue())));
                                                companyMoney = companyMoney.add(tcMoney);
                                            } else if (dlmd.getDriverLevelMoneyType()
                                                .equals(DriverLevelMoneyType.ticheng)) {// 比例
                                                BigDecimal tcMoney = _money
                                                    .multiply(dlmd.getCommission())
                                                    .divide(new BigDecimal(100));
                                                companyMoney = companyMoney.add(tcMoney);
                                            }
                                        }
                                    }
                                }

                                if (realCash.compareTo(companyMoney) == -1) {
                                    companyMoney = realCash;
                                    money = BigDecimal.ZERO;
                                    sbmemo.append("金额不足，公司实际提成" + companyMoney + "元。");
                                } else {
                                    money = realCash.subtract(companyMoney);
                                }

                                if (null != coupon) {
                                    sbmemo.append("客户使用了面值" + couponRuleMoney + "元的优惠劵，");
                                    if (couponTicheng) {
                                        sbmemo.append("优惠劵参与提成计算");
                                    } else {
                                        sbmemo.append("优惠劵不参与提成计算");
                                    }
                                }

                                driver.setVirtual(driver.getVirtual().subtract(companyMoney));

                                if (wxMoney.compareTo(BigDecimal.ZERO) == 1) {// 现金支付 多减去客户经理的钱
                                    driver.setVirtual(driver.getVirtual().subtract(wxMoney));
                                    companyMoney = companyMoney.add(wxMoney);
                                }
                                driverMapper
                                    .updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                                // 扣费记录
                                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                driverPaymentsRecord.setMoney(companyMoney);
                                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                driverPaymentsRecord
                                    .setRecordType(DriverPaymentsRecord.CONSUMED_TYPE_ORDER);
                                driverPaymentsRecord.setDriverId(driver.getId());
                                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                                driverPaymentsRecord.setOrderId(order.getId());
                                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                                driverPaymentsRecord
                                    .setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                                driverPaymentsRecord.setMemo(sbmemo.toString() + wxMemo);
                                driverPaymentsRecord
                                    .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                driverPaymentsRecord
                                    .setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                                driverPaymentsRecord.setHappend(new Date());
                                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                                // 订单财务记录
                                orderFinishedInfo
                                    .setDriverMoney(realCash.subtract(companyMoney).add(wxMoney));
                                orderFinishedInfo.setCompanyMoney(
                                    order.getCashMoney()
                                        .subtract(orderFinishedInfo.getDriverMoney())
                                        .subtract(orderFinishedInfo.getWxManagerMoney()));
                                // 订单财务记录
                            } else if (order.getPayType().compareTo(PayType.sign) == 0) {// 签单

                                BigDecimal money = BigDecimal.ZERO;
                                BigDecimal companyMoney = BigDecimal.ZERO;// 公司所得金额

                                StringBuilder sbmemo = new StringBuilder();
                                sbmemo.append(
                                    "订单【" + order.getOrderNumber() + "】，客户【" + order.getClientName()
                                        + "("
                                        + order.getClientPhone() + ")】，");

                                sbmemo.append("签单支付，");

                                if (!CollectionUtils
                                    .isEmpty(moneyTimeDetail.getDriverLevelMoneyDetails())) {

                                    for (DriverLevelMoneyDetail dlmd : moneyTimeDetail
                                        .getDriverLevelMoneyDetails()) {
                                        if (realCash.doubleValue() >= dlmd.getFromMoney()
                                            .doubleValue()) {

                                            BigDecimal _money = BigDecimal.ZERO;
                                            if (realCash.doubleValue() >= dlmd.getToMoney()
                                                .doubleValue()) {
                                                _money = dlmd.getToMoney()
                                                    .subtract(dlmd.getFromMoney());
                                            } else {
                                                _money = realCash.subtract(dlmd.getFromMoney());
                                            }

                                            if (dlmd.getDriverLevelMoneyType()
                                                .equals(DriverLevelMoneyType.guding)) {// 固定
                                                BigDecimal tcMoney = dlmd.getMoney()
                                                    .multiply(
                                                        new BigDecimal((int) (_money.doubleValue()
                                                            / dlmd.getMoneyUnit().doubleValue())));
                                                companyMoney = companyMoney.add(tcMoney);
                                            } else if (dlmd.getDriverLevelMoneyType()
                                                .equals(DriverLevelMoneyType.ticheng)) {// 比例
                                                BigDecimal tcMoney = _money
                                                    .multiply(dlmd.getCommission())
                                                    .divide(new BigDecimal(100));
                                                companyMoney = companyMoney.add(tcMoney);
                                            }
                                        }
                                    }
                                }

                                if (realCash.compareTo(companyMoney) == -1) {
                                    companyMoney = realCash;
                                    money = BigDecimal.ZERO;
                                    sbmemo.append("金额不足，公司实际提成" + companyMoney + "元。");
                                } else {
                                    money = realCash.subtract(companyMoney);
                                }

                                if (null != coupon) {
                                    sbmemo.append("客户使用了面值" + couponRuleMoney + "元的优惠劵，");
                                    if (couponTicheng) {
                                        sbmemo.append("优惠劵参与提成计算");
                                    } else {
                                        sbmemo.append("优惠劵不参与提成计算");
                                    }
                                }

                                driver.setVirtual(driver.getVirtual().add(money));
                                driverMapper
                                    .updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                driverPaymentsRecord.setMoney(money);
                                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                driverPaymentsRecord
                                    .setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                                driverPaymentsRecord.setDriverId(driver.getId());
                                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                                driverPaymentsRecord.setOrderId(order.getId());
                                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                                driverPaymentsRecord
                                    .setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                                driverPaymentsRecord.setMemo(sbmemo.toString() + wxMemo);
                                driverPaymentsRecord
                                    .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                driverPaymentsRecord
                                    .setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                                driverPaymentsRecord.setHappend(new Date());
                                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                                // 订单财务记录
                                orderFinishedInfo.setDriverMoney(driverPaymentsRecord.getMoney());
                                orderFinishedInfo.setCompanyMoney(
                                    order.getSignMoney()
                                        .subtract(orderFinishedInfo.getDriverMoney())
                                        .subtract(orderFinishedInfo.getWxManagerMoney()));
                                // 订单财务记录

                            } else if (order.getPayType().compareTo(PayType.balance) == 0) {// 余额

                                if (order.getPayTypeDetails()
                                    .equals(PayTypeDetails.balance_cash)) {// 余额+现金

                                    BigDecimal money = BigDecimal.ZERO;
                                    BigDecimal companyMoney = BigDecimal.ZERO;// 公司所得金额

                                    BigDecimal cashMoney = order.getCashMoney();

                                    StringBuilder sbmemo = new StringBuilder();
                                    sbmemo.append("订单【" + order.getOrderNumber() + "】，客户【" + order
                                        .getClientName() + "("
                                        + order.getClientPhone() + ")】，");
                                    sbmemo.append("余额(" + order.getBalanceMoney() + "元)+现金(" + order
                                        .getCashMoney()
                                        + "元)支付。");

                                    if (!CollectionUtils
                                        .isEmpty(moneyTimeDetail.getDriverLevelMoneyDetails())) {

                                        for (DriverLevelMoneyDetail dlmd : moneyTimeDetail
                                            .getDriverLevelMoneyDetails()) {
                                            if (realCash.doubleValue() >= dlmd.getFromMoney()
                                                .doubleValue()) {

                                                BigDecimal _money = BigDecimal.ZERO;
                                                if (realCash.doubleValue() >= dlmd.getToMoney()
                                                    .doubleValue()) {
                                                    _money = dlmd.getToMoney()
                                                        .subtract(dlmd.getFromMoney());
                                                } else {
                                                    _money = realCash.subtract(dlmd.getFromMoney());
                                                }

                                                if (dlmd.getDriverLevelMoneyType()
                                                    .equals(DriverLevelMoneyType.guding)) {// 固定
                                                    BigDecimal tcMoney = dlmd.getMoney()
                                                        .multiply(new BigDecimal(
                                                            (int) (_money.doubleValue()
                                                                / dlmd.getMoneyUnit()
                                                                .doubleValue())));
                                                    companyMoney = companyMoney.add(tcMoney);
                                                } else if (dlmd.getDriverLevelMoneyType()
                                                    .equals(DriverLevelMoneyType.ticheng)) {// 比例
                                                    BigDecimal tcMoney = _money
                                                        .multiply(dlmd.getCommission())
                                                        .divide(new BigDecimal(100));
                                                    companyMoney = companyMoney.add(tcMoney);
                                                }
                                            }
                                        }
                                    }

                                    if (realCash.compareTo(companyMoney) == -1) {
                                        companyMoney = realCash;
                                        money = BigDecimal.ZERO;
                                        sbmemo.append("金额不足，公司实际提成" + companyMoney + "元。");
                                    } else {
                                        money = realCash.subtract(companyMoney);
                                    }

                                    if (null != coupon) {
                                        sbmemo.append("客户使用了面值" + couponRuleMoney + "元的优惠劵，");
                                        if (couponTicheng) {
                                            sbmemo.append("优惠劵参与提成计算");
                                        } else {
                                            sbmemo.append("优惠劵不参与提成计算");
                                        }
                                    }

                                    if (cashMoney.compareTo(money) == 1
                                        || cashMoney.compareTo(money) == 0) {// 服务人员手中金额大于等于服务人员应得金额
                                        driver.setVirtual(driver.getVirtual()
                                            .subtract(cashMoney.subtract(money)));
                                        driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(),
                                            driver.getId());
                                        // 扣费记录
                                        DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                        driverPaymentsRecord.setMoney(cashMoney.subtract(money));
                                        driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                        driverPaymentsRecord.setRecordType(
                                            DriverPaymentsRecord.CONSUMED_TYPE_ORDER);
                                        driverPaymentsRecord.setDriverId(driver.getId());
                                        driverPaymentsRecord
                                            .setDriverRealName(driver.getRealname());
                                        driverPaymentsRecord
                                            .setDriverUserName(driver.getUsername());
                                        driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                        driverPaymentsRecord
                                            .setDriverCompanyId(driver.getCompanyId());
                                        driverPaymentsRecord.setOrderId(order.getId());
                                        driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                                        driverPaymentsRecord
                                            .setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                        driverPaymentsRecord
                                            .setOrderCompanyId(order.getCompanyId());
                                        driverPaymentsRecord.setMemo(sbmemo.toString() + wxMemo);
                                        driverPaymentsRecord
                                            .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                        driverPaymentsRecord
                                            .setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                                        driverPaymentsRecord.setHappend(new Date());
                                        driverPaymentsRecordMapper
                                            .insertRecord(driverPaymentsRecord);

                                        // 订单财务记录
                                        orderFinishedInfo.setDriverMoney(money);
                                        orderFinishedInfo.setCompanyMoney(cashMoney.subtract(money)
                                            .multiply(new BigDecimal(-1))
                                            .add(order.getBalanceMoney()
                                                .subtract(orderFinishedInfo.getWxManagerMoney())));
                                        // 订单财务记录
                                    } else {
                                        driver.setVirtual(
                                            driver.getVirtual().add(money.subtract(cashMoney)));
                                        driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(),
                                            driver.getId());

                                        DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                        driverPaymentsRecord.setMoney(money.subtract(cashMoney));
                                        driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                        driverPaymentsRecord.setRecordType(
                                            DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                                        driverPaymentsRecord.setDriverId(driver.getId());
                                        driverPaymentsRecord
                                            .setDriverRealName(driver.getRealname());
                                        driverPaymentsRecord
                                            .setDriverUserName(driver.getUsername());
                                        driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                        driverPaymentsRecord
                                            .setDriverCompanyId(driver.getCompanyId());
                                        driverPaymentsRecord.setOrderId(order.getId());
                                        driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                                        driverPaymentsRecord
                                            .setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                        driverPaymentsRecord
                                            .setOrderCompanyId(order.getCompanyId());
                                        driverPaymentsRecord.setMemo(sbmemo.toString() + wxMemo);
                                        driverPaymentsRecord
                                            .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                        driverPaymentsRecord
                                            .setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                                        driverPaymentsRecord.setHappend(new Date());
                                        driverPaymentsRecordMapper
                                            .insertRecord(driverPaymentsRecord);

                                        // 订单财务记录
                                        orderFinishedInfo.setDriverMoney(
                                            order.getCashMoney()
                                                .add(driverPaymentsRecord.getMoney()));
                                        orderFinishedInfo.setCompanyMoney(
                                            order.getBalanceMoney()
                                                .subtract(driverPaymentsRecord.getMoney())
                                                .subtract(orderFinishedInfo.getWxManagerMoney()));
                                        // 订单财务记录
                                    }
                                } else {

                                    BigDecimal money = BigDecimal.ZERO;
                                    BigDecimal companyMoney = BigDecimal.ZERO;// 公司所得金额

                                    StringBuilder sbmemo = new StringBuilder();
                                    sbmemo.append("订单【" + order.getOrderNumber() + "】，客户【" + order
                                        .getClientName() + "("
                                        + order.getClientPhone() + ")】，");

                                    sbmemo.append("余额支付，");

                                    if (!CollectionUtils
                                        .isEmpty(moneyTimeDetail.getDriverLevelMoneyDetails())) {

                                        for (DriverLevelMoneyDetail dlmd : moneyTimeDetail
                                            .getDriverLevelMoneyDetails()) {
                                            if (realCash.doubleValue() >= dlmd.getFromMoney()
                                                .doubleValue()) {

                                                BigDecimal _money = BigDecimal.ZERO;
                                                if (realCash.doubleValue() >= dlmd.getToMoney()
                                                    .doubleValue()) {
                                                    _money = dlmd.getToMoney()
                                                        .subtract(dlmd.getFromMoney());
                                                } else {
                                                    _money = realCash.subtract(dlmd.getFromMoney());
                                                }

                                                if (dlmd.getDriverLevelMoneyType()
                                                    .equals(DriverLevelMoneyType.guding)) {// 固定
                                                    BigDecimal tcMoney = dlmd.getMoney()
                                                        .multiply(new BigDecimal(
                                                            (int) (_money.doubleValue()
                                                                / dlmd.getMoneyUnit()
                                                                .doubleValue())));
                                                    companyMoney = companyMoney.add(tcMoney);
                                                } else if (dlmd.getDriverLevelMoneyType()
                                                    .equals(DriverLevelMoneyType.ticheng)) {// 比例
                                                    BigDecimal tcMoney = _money
                                                        .multiply(dlmd.getCommission())
                                                        .divide(new BigDecimal(100));
                                                    companyMoney = companyMoney.add(tcMoney);
                                                }
                                            }
                                        }
                                    }

                                    if (realCash.compareTo(companyMoney) == -1) {
                                        companyMoney = realCash;
                                        money = BigDecimal.ZERO;
                                        sbmemo.append("金额不足，公司实际提成" + companyMoney + "元。");
                                    } else {
                                        money = realCash.subtract(companyMoney);
                                    }

                                    if (null != coupon) {
                                        sbmemo.append("客户使用了面值" + couponRuleMoney + "元的优惠劵，");
                                        if (couponTicheng) {
                                            sbmemo.append("优惠劵参与提成计算");
                                        } else {
                                            sbmemo.append("优惠劵不参与提成计算");
                                        }
                                    }

                                    driver.setVirtual(driver.getVirtual().add(money));
                                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(),
                                        driver.getId());

                                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                                    driverPaymentsRecord.setMoney(money);
                                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                                    driverPaymentsRecord
                                        .setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                                    driverPaymentsRecord.setDriverId(driver.getId());
                                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                                    driverPaymentsRecord.setOrderId(order.getId());
                                    driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                                    driverPaymentsRecord
                                        .setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                                    driverPaymentsRecord.setMemo(sbmemo.toString() + wxMemo);
                                    driverPaymentsRecord
                                        .setOperating(DriverPaymentsRecord.OPERATING_SYS);
                                    driverPaymentsRecord
                                        .setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                                    driverPaymentsRecord.setHappend(new Date());
                                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                                    // 订单财务记录
                                    orderFinishedInfo
                                        .setDriverMoney(driverPaymentsRecord.getMoney());
                                    orderFinishedInfo.setCompanyMoney(
                                        order.getBalanceMoney()
                                            .subtract(orderFinishedInfo.getDriverMoney())
                                            .subtract(orderFinishedInfo.getWxManagerMoney()));
                                    // 订单财务记录
                                }

                            }
                        }

                    } else {
                        // 订单财务记录
                        orderFinishedInfo.setDriverMoney(BigDecimal.ZERO);
                        orderFinishedInfo
                            .setCompanyMoney(order.getCashMoney().add(order.getSignMoney())
                                .add(order.getBalanceMoney())
                                .subtract(orderFinishedInfo.getWxManagerMoney()));
                        // 订单财务记录
                    }

                } else {
                    // 订单财务记录
                    orderFinishedInfo.setDriverMoney(BigDecimal.ZERO);
                    orderFinishedInfo.setCompanyMoney(order.getCashMoney().add(order.getSignMoney())
                        .add(order.getBalanceMoney())
                        .subtract(orderFinishedInfo.getWxManagerMoney()));
                    // 订单财务记录
                }
            } else {
                // 订单财务记录
                orderFinishedInfo.setDriverMoney(BigDecimal.ZERO);
                orderFinishedInfo.setCompanyMoney(order.getCashMoney().add(order.getSignMoney())
                    .add(order.getBalanceMoney()).subtract(orderFinishedInfo.getWxManagerMoney()));
                // 订单财务记录
            }
        } else {
            // 订单财务记录
            orderFinishedInfo.setDriverMoney(BigDecimal.ZERO);
            orderFinishedInfo.setCompanyMoney(order.getCashMoney().add(order.getSignMoney())
                .add(order.getBalanceMoney()).subtract(orderFinishedInfo.getWxManagerMoney()));
            // 订单财务记录
        }
        if (null != driver) {
            if (setting.getInfoFee() != 0) {
                if (null != setting.getInfoFeeType() && setting.getInfoFeeType()
                    .equals(InfoFeeType.finishTask)) {
                    driver.setVirtual(
                        driver.getVirtual().subtract(new BigDecimal(setting.getInfoFee())));
                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                    // 扣费记录
                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                    driverPaymentsRecord.setMoney(new BigDecimal(setting.getInfoFee()));
                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                    driverPaymentsRecord
                        .setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                    driverPaymentsRecord.setDriverId(driver.getId());
                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                    driverPaymentsRecord.setOrderId(order.getId());
                    driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                    driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                    driverPaymentsRecord.setMemo("扣除公司所得保险费/信息费" + setting.getInfoFee() + "元。");
                    driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                    driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                    driverPaymentsRecord.setHappend(new Date());
                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                    // 财务记录（保险费/信息费）
                    Company mainCompany = companyMapper.selectMainCompany();
                    DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                    FinancialRecord financialRecord = new FinancialRecord();
                    StringBuilder sb_f = new StringBuilder();
                    sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 保险费/信息费
                    sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                    sb_f.append(format_f.format(new Date()));// 年月日时间
                    sb_f.append(OrderNumberConfig
                        .padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                    financialRecord.setCode(sb_f.toString());
                    financialRecord.setCompanyId(mainCompany.getId());
                    financialRecord.setCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setOrderCompanyId(mainCompany.getId());
                    financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setMemo(
                        "订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                            + order.getOrderNumber() + "</a>】保险费/信息费");
                    financialRecord.setMoney(new BigDecimal(setting.getInfoFee()));
                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                    financialRecord.setWho(driver.getRealname());
                    financialRecord.setOrderId(order.getId());
                    financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                    financialRecordMapper.insertRecord(financialRecord);

                    // 订单财务记录
                    orderFinishedInfo
                        .setInfoFee(orderFinishedInfo.getInfoFee()
                            .add(new BigDecimal(setting.getInfoFee())));
                    // 订单财务记录
                }
            }

        }

        // 订单财务记录
        orderFinishedInfoMapper.insertRecord(orderFinishedInfo);
        // 订单财务记录

        Passenger passenger = null;
        Result<Passenger> result_p = passengerApi
            .findOnePassengerByPhone(order.getClientPhone(), settingUtils.get());
        passenger = result_p.getResult();
        if (null != passenger) {

            if (!StringUtils.isBlank(order.getCarNumber())) {
                passenger.setPlateNumber(order.getCarNumber());
            }
            if (order.getHasToPlace()) {
                Result<PassengerAddress> result_address = passengerApi
                    .findPassengerToPlace(passenger.getId(),
                        PassengerAddress.TYPE_ADDRESS_OTHER, settingUtils.get());
                PassengerAddress passengerAddress = result_address.getResult();
                if (null == passengerAddress) {
                    passengerApi.addPassengerToPlace(passenger.getId(), order.getToPlace(),
                        order.getToPlaceLatitude(),
                        order.getToPlaceLongitude(), PassengerAddress.TYPE_ADDRESS_OTHER,
                        settingUtils.get());
                } else {
                    passengerApi.updatePassengerToPlace(passenger.getId(), passengerAddress.getId(),
                        order.getToPlace(),
                        order.getToPlaceLatitude(), order.getToPlaceLongitude(),
                        PassengerAddress.TYPE_ADDRESS_OTHER, settingUtils.get());
                }
            }

            BigDecimal xiaofeiMoney = BigDecimal.ZERO;
            String memo = "";

            if (order.getPayTypeDetails().equals(PayTypeDetails.coupon_cash)) {
                if (null != coupon) {
                    if (couponRuleMoney.compareTo(order.getRealCash()) == -1) {
                        xiaofeiMoney = order.getSignMoney();
                        memo = "使用优惠劵(" + couponRuleMoney + "元)+现金("
                            + order.getCashMoney().setScale(2, BigDecimal.ROUND_HALF_UP).toString()
                            + "元)消费";
                    } else {
                        xiaofeiMoney = BigDecimal.ZERO;
                        memo = "使用优惠劵(" + couponRuleMoney + "元)+现金(0元)消费";
                    }
                    coupon.setStatus(Coupon.COUPON_STATUS_HASUSED);
                    salesApi.updateCoupon(coupon);
                }
            } else if (order.getPayTypeDetails().equals(PayTypeDetails.cash)) {
                xiaofeiMoney = order.getRealCash();
                memo =
                    "使用现金(" + order.getRealCash().setScale(2, BigDecimal.ROUND_HALF_UP).toString()
                        + "元)消费";
            } else if (order.getPayTypeDetails().equals(PayTypeDetails.coupon_sign)) {
                if (null != coupon) {
                    if (couponRuleMoney.compareTo(order.getRealCash()) == -1) {
                        xiaofeiMoney = order.getSignMoney();
                        memo = "使用优惠劵(" + couponRuleMoney + "元)+签单("
                            + order.getSignMoney().setScale(2, BigDecimal.ROUND_HALF_UP).toString()
                            + "元)消费";
                    } else {
                        xiaofeiMoney = BigDecimal.ZERO;
                        memo = "使用优惠劵(" + couponRuleMoney + "元)+签单(0元)消费";
                    }
                    coupon.setStatus(Coupon.COUPON_STATUS_HASUSED);
                    salesApi.updateCoupon(coupon);
                }
            } else if (order.getPayTypeDetails().equals(PayTypeDetails.sign)) {
                xiaofeiMoney = order.getRealCash();
                memo =
                    "使用签单(" + order.getRealCash().setScale(2, BigDecimal.ROUND_HALF_UP).toString()
                        + "元)消费";
            } else if (order.getPayTypeDetails().equals(PayTypeDetails.balance_cash)) {
                xiaofeiMoney = order.getBalanceMoney();
                memo = "使用余额(" + order.getBalanceMoney().setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toString() + "元)+现金("
                    + order.getCashMoney().setScale(2, BigDecimal.ROUND_HALF_UP).toString()
                    + "元)消费";
            } else if (order.getPayTypeDetails().equals(PayTypeDetails.coupon_balance)) {
                if (null != coupon) {
                    if (couponRuleMoney.compareTo(order.getRealCash()) == -1) {
                        xiaofeiMoney = order.getRealCash().subtract(couponRuleMoney);
                        memo = "使用优惠劵(" + couponRuleMoney + "元)+余额("
                            + order.getBalanceMoney().setScale(2, BigDecimal.ROUND_HALF_UP)
                            .toString() + "元)消费";
                    } else {
                        xiaofeiMoney = BigDecimal.ZERO;
                        memo = "使用优惠劵(" + couponRuleMoney + "元)+余额(0元)消费";
                    }
                    coupon.setStatus(Coupon.COUPON_STATUS_HASUSED);
                    salesApi.updateCoupon(coupon);
                }
            } else if (order.getPayTypeDetails().equals(PayTypeDetails.balance)) {
                xiaofeiMoney = order.getRealCash();
                memo =
                    "使用余额(" + order.getRealCash().setScale(2, BigDecimal.ROUND_HALF_UP).toString()
                        + "元)消费";
            }

            if (PayType.sign.equals(order.getPayType()) || PayType.balance
                .equals(order.getPayType())) {// 客户签单或余额消费
                passenger.setMileage(passenger.getMileage() + order.getMileage());

                PassengerAccount.PayType payType = PassengerAccount.PayType.PAYTYPE_BALANCE;
                if (PayType.sign.equals(order.getPayType())) {
                    payType = PassengerAccount.PayType.PAYTYPE_SIGN;
                }

                PassengerAccount passengerAccount = null;
                if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {

                    passenger.setDrivingNumberTimes(passenger.getDrivingNumberTimes() + 1);

                    Result<PassengerAccount> result_account = passengerApi
                        .createPassengerAccount(passenger, null,
                            xiaofeiMoney.negate(), payType, PassengerAccount.OPERATING_SYS, memo,
                            order.getId(),
                            order.getOrderNumber(), PassengerAccount.ORDER_TYPE_DAIJIA, null, true,
                            false,
                            settingUtils.get());
                    passengerAccount = result_account.getResult();

                } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                    Enterprise enterprise = passengerApi
                        .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                        .getResult();
                    if (null != enterprise) {

                        enterprise.setDrivingNumberTimes(enterprise.getDrivingNumberTimes() + 1);
                        passengerApi.updateEnterprise(enterprise, settingUtils.get());

                        Result<PassengerAccount> result_account = passengerApi
                            .createEnterpriseAccount(enterprise,
                                xiaofeiMoney.negate(), payType, PassengerAccount.OPERATING_SYS,
                                memo, order.getId(),
                                order.getOrderNumber(), PassengerAccount.ORDER_TYPE_DAIJIA, null,
                                true, false,
                                settingUtils.get());
                        passengerAccount = result_account.getResult();

                    }
                }

                passengerApi.createReceipt(passenger,
                    order.getCashMoney().add(order.getBalanceMoney()).add(order.getSignMoney()),
                    settingUtils.get());

                // 增加发票金额
                // memberMapper.updateAlreadyMoney(member.getId(),
                // member.getAlreadyMoney().add(order.getCashMoney()).add(order.getBalanceMoney()).add(order.getSignMoney()));
                // memberMapper.addVirtualByPrimaryKey(xiaofeiMoney.negate(),
                // member.getId());
                // memberMapper.incCompleteTimesByPrimaryKey(member.getId());
                // memberMapper.addMileageByPrimaryKey(order.getMileage(),
                // member.getId());
                // member.setVirtual(member.getVirtual().subtract(xiaofeiMoney));
                //
                // MemberConsumedRecord memberConsumedRecord=new MemberConsumedRecord();
                // memberConsumedRecord.setMemberId(member.getId());
                // memberConsumedRecord.setMemberAccountId(memberaccount.getId());
                // memberConsumedRecord.setMoney(order.getRealCash());
                // memberConsumedRecord.setOrderId(order.getId());
                // memberConsumedRecord.setOrderNumber(order.getOrderNumber());
                // memberConsumedRecord.setAfterMoney(member.getVirtual());
                // if(PayType.sign.equals(order.getPayType())){
                // memberConsumedRecord.setPayType(MemberConsumedRecord.PAYTYPE_SIGN);
                // }
                // else{
                // memberConsumedRecord.setPayType(MemberConsumedRecord.PAYTYPE_BALANCE);
                // }
                // memberConsumedRecord.setMemo(memo);
                // memberConsumedRecordMapper.insertRecord(memberConsumedRecord);
                //
                // /*新纪录*/
                // MemberPaymentsRecord memberPaymentsRecord=new MemberPaymentsRecord();
                // memberPaymentsRecord.setMemberId(member.getId());
                // memberPaymentsRecord.setMemberAccountId(memberaccount.getId());
                // memberPaymentsRecord.setMoney(order.getRealCash().negate());
                // memberPaymentsRecord.setAfterMoney(member.getVirtual());
                // memberPaymentsRecord.setOrderId(order.getId());
                // memberPaymentsRecord.setOrderNumber(order.getOrderNumber());
                // memberPaymentsRecord.setOperating(MemberPaymentsRecord.OPERATING_SYS);
                // if(PayType.sign.equals(order.getPayType())){
                // memberPaymentsRecord.setPaymentType(MemberPaymentsRecord.PaymentType.PAYTYPE_SIGN);
                // }
                // else{
                // memberPaymentsRecord.setPaymentType(MemberPaymentsRecord.PaymentType.PAYTYPE_BALANCE);
                // }
                // memberPaymentsRecord.setMemo(memo);
                // memberPaymentsRecordMapper.insertRecord(memberPaymentsRecord);
                // /*新纪录*/
                //
                // 客户扣费短信
                if (null != passengerAccount) {
                    if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                        MemberConsumedEvent consumedEvent = new MemberConsumedEvent(
                            passengerAccount, null);
                        applicationEventMulticaster.multicastEvent(consumedEvent);
                    } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                        MemberConsumedEvent consumedEvent = new MemberConsumedEvent(
                            passengerAccount,
                            passenger.getPhone());
                        applicationEventMulticaster.multicastEvent(consumedEvent);
                    }
                }

            } else if (PayType.cash.equals(order.getPayType())) {// 客户现金消费
                passenger.setMileage(passenger.getMileage() + order.getMileage());

                if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {

                    passenger.setDrivingNumberTimes(passenger.getDrivingNumberTimes() + 1);

                    passengerApi.createPassengerAccount(passenger, null, xiaofeiMoney.negate(),
                        PassengerAccount.PayType.PAYTYPE_CASH, PassengerAccount.OPERATING_SYS, memo,
                        order.getId(),
                        order.getOrderNumber(), PassengerAccount.ORDER_TYPE_DAIJIA, null, false,
                        false,
                        settingUtils.get());

                } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                    Enterprise enterprise = passengerApi
                        .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                        .getResult();
                    if (null != enterprise) {

                        enterprise.setDrivingNumberTimes(enterprise.getDrivingNumberTimes() + 1);
                        passengerApi.updateEnterprise(enterprise, settingUtils.get());

                        passengerApi.createEnterpriseAccount(enterprise, xiaofeiMoney.negate(),
                            PassengerAccount.PayType.PAYTYPE_CASH, PassengerAccount.OPERATING_SYS,
                            memo,
                            order.getId(), order.getOrderNumber(),
                            PassengerAccount.ORDER_TYPE_DAIJIA, null, false,
                            false, settingUtils.get());

                    }
                }

                passengerApi.createReceipt(passenger,
                    order.getCashMoney().add(order.getBalanceMoney()).add(order.getSignMoney()),
                    settingUtils.get());

                // 增加发票金额
                // memberMapper.updateAlreadyMoney(member.getId(),
                // member.getAlreadyMoney().add(order.getCashMoney()).add(order.getBalanceMoney()).add(order.getSignMoney()));
                // memberMapper.incCompleteTimesByPrimaryKey(member.getId());
                //
                // MemberConsumedRecord memberConsumedRecord=new MemberConsumedRecord();
                // memberConsumedRecord.setMemberId(member.getId());
                // memberConsumedRecord.setMemberAccountId(memberaccount.getId());
                // memberConsumedRecord.setMoney(order.getRealCash());
                // memberConsumedRecord.setOrderId(order.getId());
                // memberConsumedRecord.setOrderNumber(order.getOrderNumber());
                // memberConsumedRecord.setAfterMoney(member.getVirtual());
                // memberConsumedRecord.setPayType(MemberConsumedRecord.PAYTYPE_CASH);
                // memberConsumedRecord.setMemo(memo);
                // memberConsumedRecordMapper.insertRecord(memberConsumedRecord);
                //
                // /*新纪录*/
                // MemberPaymentsRecord memberPaymentsRecord=new MemberPaymentsRecord();
                // memberPaymentsRecord.setMemberId(member.getId());
                // memberPaymentsRecord.setMemberAccountId(memberaccount.getId());
                // memberPaymentsRecord.setMoney(order.getRealCash().multiply(new
                // BigDecimal(-1)));
                // memberPaymentsRecord.setAfterMoney(member.getVirtual());
                // memberPaymentsRecord.setOrderId(order.getId());
                // memberPaymentsRecord.setOrderNumber(order.getOrderNumber());
                // memberPaymentsRecord.setOperating(MemberPaymentsRecord.OPERATING_SYS);
                // memberPaymentsRecord.setPaymentType(MemberPaymentsRecord.PaymentType.PAYTYPE_CASH);
                // memberPaymentsRecord.setMemo(memo);
                // memberPaymentsRecordMapper.insertRecord(memberPaymentsRecord);
                /* 新纪录 */

            }

            passengerApi.updatePersonal(passenger, settingUtils.get());
        }

        // 财务记录
        boolean companyGetAll = false;// 公司是否的全部
        DateFormat format = new SimpleDateFormat("yyyyMMdd");
        if (null != driver) {
            if (null != driver.getType() && Driver.DRIVER_TYPR_PARTTIME.equals(driver.getType())) {

                DriverChoseLevel driverChoseLevel = null;
                DriverChoseLevelCar driverChoseLevelCar = null;
                driverChoseLevel = driverChoseLevelMapper.selectByDriverAndCompany(driver.getId(),
                    order.getCompanyId());

                if (null != driverChoseLevel || null != driverChoseLevelCar) {

                    DriverLevel driverLevel = null;
                    if (null != driverChoseLevel) {
                        if (driverChoseLevel.getDriverlevelId() == 0) {// 始终使用本公司提成
                            DriverChoseLevel driverChoseLevel2 = driverChoseLevelMapper
                                .selectByDriverAndCompany(driver.getId(), driver.getCompanyId());
                            if (null != driverChoseLevel2) {
                                driverLevel = driverLevelMapper
                                    .selectByPrimaryKey(driverChoseLevel2.getDriverlevelId());
                            }
                        } else {
                            driverLevel = driverLevelMapper
                                .selectByPrimaryKey(driverChoseLevel.getDriverlevelId());
                        }
                    } else if (null != driverChoseLevelCar) {
                        if (driverChoseLevelCar.getDriverlevelId() == 0) {// 始终使用本公司提成
                            DriverChoseLevelCar driverChoseLevelCar2 = driverChoseLevelCarMapper
                                .selectByDriverAndCompany(driver.getId(), driver.getCompanyId());
                            if (null != driverChoseLevelCar2) {
                                driverLevel = driverLevelMapper
                                    .selectByPrimaryKey(driverChoseLevelCar2.getDriverlevelId());
                            }
                        } else {
                            driverLevel = driverLevelMapper
                                .selectByPrimaryKey(driverChoseLevelCar.getDriverlevelId());
                        }
                    }

                    DriverLevelDetail detail = null;
                    DriverLevelMoneyTimeDetail moneyTimeDetail = null;

                    if (null != driverLevel) {
                        if (driverLevel.getType().equals(0)) {
                            driverLevel.setDriverLevelDetails(
                                driverLevelDetailMapper.selectByDriverLevel(driverLevel.getId()));
                            if (driverLevel.getTimePoint().equals(TimePoint.serviceTime)) {
                                detail = driverLevel.getDeatil(order.getServerTime());
                            } else if (driverLevel.getTimePoint().equals(TimePoint.startDrive)) {
                                detail = driverLevel.getDeatil(travelDate);
                            } else if (driverLevel.getTimePoint().equals(TimePoint.finishTime)) {
                                detail = driverLevel.getDeatil(order.getFinishTime());
                            }
                        } else if (driverLevel.getType().equals(1)) {
                            driverLevel.setDriverLevelMoneyTimeDetails(
                                driverLevelMoneyTimeDetailMapper
                                    .selectByDriverLevel(driverLevel.getId()));
                            if (driverLevel.getTimePoint().equals(TimePoint.serviceTime)) {
                                moneyTimeDetail = driverLevel
                                    .getMoneyTimeDeatil(order.getServerTime());
                            } else if (driverLevel.getTimePoint().equals(TimePoint.startDrive)) {
                                moneyTimeDetail = driverLevel.getMoneyTimeDeatil(travelDate);
                            } else if (driverLevel.getTimePoint().equals(TimePoint.finishTime)) {
                                moneyTimeDetail = driverLevel
                                    .getMoneyTimeDeatil(order.getFinishTime());
                            }
                        }
                    }

                    if (null != detail) {
                        // if((detail.getDriverLevelType().equals(DriverLevelType.ticheng)
                        // && ((detail.getMinCommission().compareTo(BigDecimal.ZERO)==0) ||
                        // (detail.getMinCommission().compareTo(BigDecimal.ZERO)==1 &&
                        // order.getRealCash().compareTo(detail.getMinCommission())!=-1) ||
                        // (detail.getMinCommission().compareTo(BigDecimal.ZERO)==1 &&
                        // order.getRealCash().compareTo(detail.getMinCommission())==-1 &&
                        // detail.getLowCommission().compareTo(BigDecimal.ZERO)==1))) ||
                        // (detail.getDriverLevelType().equals(DriverLevelType.guding) &&
                        // ((detail.getMinMoney().compareTo(BigDecimal.ZERO)==0) ||
                        // (detail.getMinMoney().compareTo(BigDecimal.ZERO)==1 &&
                        // order.getRealCash().compareTo(detail.getMinMoney())!=-1) ||
                        // (detail.getMinMoney().compareTo(BigDecimal.ZERO)==1 &&
                        // order.getRealCash().compareTo(detail.getMinMoney())==-1 &&
                        // detail.getLowMoney().compareTo(BigDecimal.ZERO)==1)))){

                        if (null != coupon && couponTicheng) {

                            if (couponRuleMoney.compareTo(order.getRealCash()) != -1
                                || order.getPayTypeDetails().equals(PayTypeDetails.coupon_sign)
                                || order.getPayTypeDetails()
                                .equals(PayTypeDetails.coupon_balance)) {

                                String memo =
                                    "订单号【<a target='_blank' href='/order/detail/" + order.getId()
                                        + "'>"
                                        + order.getOrderNumber() + "</a>】。";

                                BigDecimal money = BigDecimal.ZERO;
                                if (detail.getDriverLevelType().equals(DriverLevelType.ticheng)) {
                                    if (order.getRealCash().compareTo(detail.getMinCommission())
                                        == -1) {
                                        money = realCash.subtract(detail.getLowCommission());
                                    } else {
                                        money = realCash.multiply(
                                            new BigDecimal(100).subtract(detail.getCommission()))
                                            .divide(new BigDecimal(100));
                                    }
                                } else if (detail.getDriverLevelType()
                                    .equals(DriverLevelType.guding)) {
                                    if (order.getRealCash().compareTo(detail.getMinMoney()) == -1) {
                                        money = realCash.subtract(detail.getLowMoney());
                                    } else {
                                        if (realCash.compareTo(detail.getMoney()) == -1) {
                                            money = BigDecimal.ZERO;
                                        } else {
                                            money = realCash.subtract(detail.getMoney());
                                        }
                                    }
                                }

                                memo += "客户使用了面值" + couponRuleMoney + "元的优惠劵，并且优惠劵参与提成，";
                                memo += "服务人员应提成" + money + "元，相应公司扣取" + money + "元。";

                                Company company = companyMapper
                                    .selectByPrimaryKey(driver.getCompanyId());
                                Company orderCompany = companyMapper
                                    .selectByPrimaryKey(order.getCompanyId());

                                FinancialRecord financialRecord = new FinancialRecord();
                                StringBuilder sb = new StringBuilder();
                                sb.append(OrderNumberConfig.FINANCIAL_ORDER);// 订单金额
                                sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);// 对象 客户
                                sb.append(format.format(new Date()));// 年月日时间
                                sb.append(OrderNumberConfig
                                    .padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                                financialRecord.setCode(sb.toString());
                                financialRecord.setCompanyId(company.getId());
                                financialRecord.setCompanyName(company.getAbbreviation());
                                financialRecord.setOrderCompanyId(orderCompany.getId());
                                financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                                financialRecord.setMemo(memo);
                                financialRecord.setMoney(money.multiply(new BigDecimal(-1)));
                                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                                if (StringUtils.isNotBlank(order.getClientName())) {
                                    financialRecord.setWho(order.getClientName());
                                } else {
                                    financialRecord.setWho(order.getClientPhone());
                                }
                                financialRecord.setOrderId(order.getId());
                                financialRecord
                                    .setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                                financialRecordMapper.insertRecord(financialRecord);
                            } else if (order.getPayTypeDetails()
                                .equals(PayTypeDetails.coupon_cash)) {
                                String memo =
                                    "订单号【<a target='_blank' href='/order/detail/" + order.getId()
                                        + "'>"
                                        + order.getOrderNumber() + "</a>】。";

                                BigDecimal money = BigDecimal.ZERO;
                                if (detail.getDriverLevelType().equals(DriverLevelType.ticheng)) {
                                    if (order.getRealCash().compareTo(detail.getMinCommission())
                                        == -1) {// 公司不提成
                                        money = detail.getLowCommission();
                                    } else {
                                        money = realCash.multiply(detail.getCommission())
                                            .divide(new BigDecimal(100));
                                    }
                                } else if (detail.getDriverLevelType()
                                    .equals(DriverLevelType.guding)) {
                                    if (order.getRealCash().compareTo(detail.getMinMoney())
                                        == -1) {// 公司不提成
                                        money = detail.getLowMoney();
                                    } else {
                                        if (realCash.compareTo(detail.getMoney()) == -1) {
                                            money = realCash;
                                        } else {
                                            money = detail.getMoney();
                                        }
                                    }
                                }

                                BigDecimal xianjin = order.getCashMoney();// 服务人员现有现金
                                BigDecimal yingde = realCash.subtract(money);// 服务人员应得提成
                                if (yingde.compareTo(BigDecimal.ZERO) == -1) {
                                    yingde = BigDecimal.ZERO;
                                }

                                memo += "客户使用了面值" + couponRuleMoney + "元的优惠劵，并且优惠劵参与提成，";
                                if (xianjin.compareTo(yingde) == -1) {// 服务人员加钱 公司减钱
                                    memo += "服务人员应提成" + yingde + "元，服务人员现有现金" + xianjin + "元，服务人员增加"
                                        + yingde.subtract(xianjin) + "元，相应公司扣取" + yingde
                                        .subtract(xianjin) + "元。";
                                } else {// 服务人员减钱 公司加钱
                                    memo += "服务人员应提成" + yingde + "元，服务人员现有现金" + xianjin + "元，服务人员扣取"
                                        + xianjin.subtract(yingde) + "元，相应公司收入" + xianjin
                                        .subtract(yingde) + "元。";
                                }

                                Company company = companyMapper
                                    .selectByPrimaryKey(driver.getCompanyId());
                                Company orderCompany = companyMapper
                                    .selectByPrimaryKey(order.getCompanyId());

                                FinancialRecord financialRecord = new FinancialRecord();
                                // 生成订单号
                                StringBuilder sb = new StringBuilder();
                                sb.append(OrderNumberConfig.FINANCIAL_TICHENG);// 提成金额
                                sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);// 对象 客户
                                sb.append(format.format(new Date()));// 年月日时间
                                sb.append(OrderNumberConfig
                                    .padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                                financialRecord.setCode(sb.toString());
                                financialRecord.setCompanyId(company.getId());
                                financialRecord.setCompanyName(company.getAbbreviation());
                                financialRecord.setOrderCompanyId(orderCompany.getId());
                                financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                                financialRecord.setMemo(memo);
                                financialRecord.setMoney(xianjin.subtract(yingde));
                                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                                if (StringUtils.isNotBlank(order.getClientName())) {
                                    financialRecord.setWho(order.getClientName());
                                } else {
                                    financialRecord.setWho(order.getClientPhone());
                                }
                                financialRecord.setOrderId(order.getId());
                                financialRecord
                                    .setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                                financialRecordMapper.insertRecord(financialRecord);

                            }

                        } else {

                            if (order.getPayType().compareTo(PayType.cash) == 0) {// 现金

                                String memo =
                                    "订单号【<a target='_blank' href='/order/detail/" + order.getId()
                                        + "'>"
                                        + order.getOrderNumber() + "</a>】收入。";

                                BigDecimal money = BigDecimal.ZERO;
                                if (detail.getDriverLevelType().equals(DriverLevelType.ticheng)) {
                                    if (order.getRealCash().compareTo(detail.getMinCommission())
                                        == -1) {
                                        money = detail.getLowCommission();
                                    } else {
                                        money = shouruMoney.multiply(detail.getCommission())
                                            .divide(new BigDecimal(100));
                                    }
                                } else if (detail.getDriverLevelType()
                                    .equals(DriverLevelType.guding)) {
                                    if (order.getRealCash().compareTo(detail.getMinMoney()) == -1) {
                                        money = detail.getLowMoney();
                                    } else {
                                        if (shouruMoney.compareTo(detail.getMoney()) == -1) {
                                            money = shouruMoney;
                                        } else {
                                            money = detail.getMoney();
                                        }
                                    }
                                }

                                if (null != coupon) {
                                    memo += "客户使用了面值" + couponRuleMoney + "元的优惠劵。";
                                }

                                Company company = companyMapper
                                    .selectByPrimaryKey(driver.getCompanyId());
                                Company orderCompany = companyMapper
                                    .selectByPrimaryKey(order.getCompanyId());

                                FinancialRecord financialRecord = new FinancialRecord();
                                // 生成订单号
                                StringBuilder sb = new StringBuilder();
                                sb.append(OrderNumberConfig.FINANCIAL_TICHENG);// 提成金额
                                sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);// 对象 客户
                                sb.append(format.format(new Date()));// 年月日时间
                                sb.append(OrderNumberConfig
                                    .padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                                financialRecord.setCode(sb.toString());
                                financialRecord.setCompanyId(company.getId());
                                financialRecord.setCompanyName(company.getAbbreviation());
                                financialRecord.setOrderCompanyId(orderCompany.getId());
                                financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                                financialRecord.setMemo(memo);
                                financialRecord.setMoney(money);
                                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                                if (StringUtils.isNotBlank(order.getClientName())) {
                                    financialRecord.setWho(order.getClientName());
                                } else {
                                    financialRecord.setWho(order.getClientPhone());
                                }
                                financialRecord.setOrderId(order.getId());
                                financialRecord
                                    .setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                                financialRecordMapper.insertRecord(financialRecord);

                            } else if (order.getPayType().compareTo(PayType.sign) == 0) {// 签单

                                String memo =
                                    "订单号【<a target='_blank' href='/order/detail/" + order.getId()
                                        + "'>"
                                        + order.getOrderNumber() + "</a>】收入。";

                                BigDecimal money = BigDecimal.ZERO;
                                if (detail.getDriverLevelType().equals(DriverLevelType.ticheng)) {
                                    if (order.getRealCash().compareTo(detail.getMinCommission())
                                        == -1) {
                                        money = detail.getLowCommission();
                                    } else {
                                        money = shouruMoney.multiply(detail.getCommission())
                                            .divide(new BigDecimal(100));
                                    }
                                } else if (detail.getDriverLevelType()
                                    .equals(DriverLevelType.guding)) {
                                    if (order.getRealCash().compareTo(detail.getMinMoney()) == -1) {
                                        money = detail.getLowMoney();
                                    } else {
                                        if (shouruMoney.compareTo(detail.getMoney()) == -1) {
                                            money = shouruMoney;
                                        } else {
                                            money = detail.getMoney();
                                        }
                                    }

                                }

                                if (null != coupon) {
                                    memo += "客户使用了面值" + couponRuleMoney + "元的优惠劵。";
                                }

                                Company company = companyMapper
                                    .selectByPrimaryKey(driver.getCompanyId());
                                Company orderCompany = companyMapper
                                    .selectByPrimaryKey(order.getCompanyId());

                                FinancialRecord financialRecord = new FinancialRecord();
                                StringBuilder sb = new StringBuilder();
                                sb.append(OrderNumberConfig.FINANCIAL_ORDER);// 订单金额
                                sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);// 对象 客户
                                sb.append(format.format(new Date()));// 年月日时间
                                sb.append(OrderNumberConfig
                                    .padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                                financialRecord.setCode(sb.toString());
                                financialRecord.setCompanyId(company.getId());
                                financialRecord.setCompanyName(company.getAbbreviation());
                                financialRecord.setOrderCompanyId(orderCompany.getId());
                                financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                                financialRecord.setMemo(memo);
                                financialRecord.setMoney(money);
                                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                                if (StringUtils.isNotBlank(order.getClientName())) {
                                    financialRecord.setWho(order.getClientName());
                                } else {
                                    financialRecord.setWho(order.getClientPhone());
                                }
                                financialRecord.setOrderId(order.getId());
                                financialRecord
                                    .setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                                financialRecordMapper.insertRecord(financialRecord);

                            } else if (order.getPayType().compareTo(PayType.balance) == 0) {// 余额

                                if (order.getPayTypeDetails()
                                    .equals(PayTypeDetails.balance_cash)) {// 余额+现金

                                    String memo =
                                        "订单号【<a target='_blank' href='/order/detail/" + order
                                            .getId() + "'>"
                                            + order.getOrderNumber() + "</a>】收入。";

                                    shouruMoney = order.getRealCash().subtract(wxMoney);
                                    BigDecimal money = BigDecimal.ZERO;
                                    if (detail.getDriverLevelType()
                                        .equals(DriverLevelType.ticheng)) {
                                        if (order.getRealCash().compareTo(detail.getMinCommission())
                                            == -1) {
                                            money = detail.getLowCommission();
                                        } else {
                                            money = shouruMoney.multiply(detail.getCommission())
                                                .divide(new BigDecimal(100));
                                        }
                                    } else if (detail.getDriverLevelType()
                                        .equals(DriverLevelType.guding)) {
                                        if (order.getRealCash().compareTo(detail.getMinMoney())
                                            == -1) {
                                            money = detail.getLowMoney();
                                        } else {
                                            if (shouruMoney.compareTo(detail.getMoney()) == -1) {
                                                money = shouruMoney;
                                            } else {
                                                money = detail.getMoney();
                                            }
                                        }
                                    }

                                    Company company = companyMapper
                                        .selectByPrimaryKey(driver.getCompanyId());
                                    Company orderCompany = companyMapper
                                        .selectByPrimaryKey(order.getCompanyId());

                                    FinancialRecord financialRecord = new FinancialRecord();
                                    StringBuilder sb = new StringBuilder();
                                    sb.append(OrderNumberConfig.FINANCIAL_ORDER);// 订单金额
                                    sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);// 对象 客户
                                    sb.append(format.format(new Date()));// 年月日时间
                                    sb.append(OrderNumberConfig.padZero(
                                        financialRecordMapper.getRunningNumber() + 1));// 流水号
                                    financialRecord.setCode(sb.toString());
                                    financialRecord.setCompanyId(company.getId());
                                    financialRecord.setCompanyName(company.getAbbreviation());
                                    financialRecord.setOrderCompanyId(orderCompany.getId());
                                    financialRecord
                                        .setOrderCompanyName(orderCompany.getAbbreviation());
                                    financialRecord.setMemo(memo);
                                    financialRecord.setMoney(money);
                                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                                    if (StringUtils.isNotBlank(order.getClientName())) {
                                        financialRecord.setWho(order.getClientName());
                                    } else {
                                        financialRecord.setWho(order.getClientPhone());
                                    }
                                    financialRecord.setOrderId(order.getId());
                                    financialRecord
                                        .setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                                    financialRecordMapper.insertRecord(financialRecord);

                                } else {
                                    String memo =
                                        "订单号【<a target='_blank' href='/order/detail/" + order
                                            .getId() + "'>"
                                            + order.getOrderNumber() + "</a>】收入。";

                                    BigDecimal money = BigDecimal.ZERO;
                                    if (detail.getDriverLevelType()
                                        .equals(DriverLevelType.ticheng)) {
                                        if (order.getRealCash().compareTo(detail.getMinCommission())
                                            == -1) {
                                            money = detail.getLowCommission();
                                        } else {
                                            money = shouruMoney.multiply(detail.getCommission())
                                                .divide(new BigDecimal(100));
                                        }
                                    } else if (detail.getDriverLevelType()
                                        .equals(DriverLevelType.guding)) {
                                        if (order.getRealCash().compareTo(detail.getMinMoney())
                                            == -1) {
                                            money = detail.getLowMoney();
                                        } else {
                                            if (shouruMoney.compareTo(detail.getMoney()) == -1) {
                                                money = shouruMoney;
                                            } else {
                                                money = detail.getMoney();
                                            }
                                        }
                                    }

                                    if (null != coupon) {
                                        memo += "客户使用了面值" + couponRuleMoney + "元的优惠劵。";
                                    }

                                    Company company = companyMapper
                                        .selectByPrimaryKey(driver.getCompanyId());
                                    Company orderCompany = companyMapper
                                        .selectByPrimaryKey(order.getCompanyId());

                                    FinancialRecord financialRecord = new FinancialRecord();
                                    StringBuilder sb = new StringBuilder();
                                    sb.append(OrderNumberConfig.FINANCIAL_ORDER);// 订单金额
                                    sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);// 对象 客户
                                    sb.append(format.format(new Date()));// 年月日时间
                                    sb.append(OrderNumberConfig.padZero(
                                        financialRecordMapper.getRunningNumber() + 1));// 流水号
                                    financialRecord.setCode(sb.toString());
                                    financialRecord.setCompanyId(company.getId());
                                    financialRecord.setCompanyName(company.getAbbreviation());
                                    financialRecord.setOrderCompanyId(orderCompany.getId());
                                    financialRecord
                                        .setOrderCompanyName(orderCompany.getAbbreviation());
                                    financialRecord.setMemo(memo);
                                    financialRecord.setMoney(money);
                                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                                    if (StringUtils.isNotBlank(order.getClientName())) {
                                        financialRecord.setWho(order.getClientName());
                                    } else {
                                        financialRecord.setWho(order.getClientPhone());
                                    }
                                    financialRecord.setOrderId(order.getId());
                                    financialRecord
                                        .setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                                    financialRecordMapper.insertRecord(financialRecord);
                                }
                            }

                        }

                        // }
                    } else if (null != moneyTimeDetail) {
                        if (null != coupon && couponTicheng) {

                            if (couponRuleMoney.compareTo(order.getRealCash()) != -1
                                || order.getPayTypeDetails().equals(PayTypeDetails.coupon_sign)
                                || order.getPayTypeDetails()
                                .equals(PayTypeDetails.coupon_balance)) {

                                String memo =
                                    "订单号【<a target='_blank' href='/order/detail/" + order.getId()
                                        + "'>"
                                        + order.getOrderNumber() + "</a>】。";

                                BigDecimal money = BigDecimal.ZERO;
                                BigDecimal companyMoney = BigDecimal.ZERO;
                                if (!CollectionUtils
                                    .isEmpty(moneyTimeDetail.getDriverLevelMoneyDetails())) {

                                    for (DriverLevelMoneyDetail dlmd : moneyTimeDetail
                                        .getDriverLevelMoneyDetails()) {
                                        if (realCash.doubleValue() >= dlmd.getFromMoney()
                                            .doubleValue()) {

                                            BigDecimal _money = BigDecimal.ZERO;
                                            if (realCash.doubleValue() >= dlmd.getToMoney()
                                                .doubleValue()) {
                                                _money = dlmd.getToMoney()
                                                    .subtract(dlmd.getFromMoney());
                                            } else {
                                                _money = realCash.subtract(dlmd.getFromMoney());
                                            }

                                            if (dlmd.getDriverLevelMoneyType()
                                                .equals(DriverLevelMoneyType.guding)) {// 固定
                                                BigDecimal tcMoney = dlmd.getMoney()
                                                    .multiply(
                                                        new BigDecimal((int) (_money.doubleValue()
                                                            / dlmd.getMoneyUnit().doubleValue())));
                                                companyMoney = companyMoney.add(tcMoney);
                                            } else if (dlmd.getDriverLevelMoneyType()
                                                .equals(DriverLevelMoneyType.ticheng)) {// 比例
                                                BigDecimal tcMoney = _money
                                                    .multiply(dlmd.getCommission())
                                                    .divide(new BigDecimal(100));
                                                companyMoney = companyMoney.add(tcMoney);
                                            }
                                        }
                                    }
                                }

                                if (realCash.compareTo(companyMoney) == -1) {
                                    companyMoney = realCash;
                                    money = BigDecimal.ZERO;
                                    memo += "金额不足，公司实际提成" + companyMoney + "元。";
                                } else {
                                    money = realCash.subtract(companyMoney);
                                }

                                memo += "客户使用了面值" + couponRuleMoney + "元的优惠劵，并且优惠劵参与提成，";
                                memo += "服务人员应提成" + money + "元，相应公司扣取" + money + "元。";

                                Company company = companyMapper
                                    .selectByPrimaryKey(driver.getCompanyId());
                                Company orderCompany = companyMapper
                                    .selectByPrimaryKey(order.getCompanyId());

                                FinancialRecord financialRecord = new FinancialRecord();
                                StringBuilder sb = new StringBuilder();
                                sb.append(OrderNumberConfig.FINANCIAL_ORDER);// 订单金额
                                sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);// 对象 客户
                                sb.append(format.format(new Date()));// 年月日时间
                                sb.append(OrderNumberConfig
                                    .padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                                financialRecord.setCode(sb.toString());
                                financialRecord.setCompanyId(company.getId());
                                financialRecord.setCompanyName(company.getAbbreviation());
                                financialRecord.setOrderCompanyId(orderCompany.getId());
                                financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                                financialRecord.setMemo(memo);
                                financialRecord.setMoney(money.multiply(new BigDecimal(-1)));
                                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                                if (StringUtils.isNotBlank(order.getClientName())) {
                                    financialRecord.setWho(order.getClientName());
                                } else {
                                    financialRecord.setWho(order.getClientPhone());
                                }
                                financialRecord.setOrderId(order.getId());
                                financialRecord
                                    .setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                                financialRecordMapper.insertRecord(financialRecord);
                            } else if (order.getPayTypeDetails()
                                .equals(PayTypeDetails.coupon_cash)) {
                                String memo =
                                    "订单号【<a target='_blank' href='/order/detail/" + order.getId()
                                        + "'>"
                                        + order.getOrderNumber() + "</a>】。";

                                BigDecimal money = BigDecimal.ZERO;
                                BigDecimal companyMoney = BigDecimal.ZERO;
                                if (!CollectionUtils
                                    .isEmpty(moneyTimeDetail.getDriverLevelMoneyDetails())) {

                                    for (DriverLevelMoneyDetail dlmd : moneyTimeDetail
                                        .getDriverLevelMoneyDetails()) {
                                        if (realCash.doubleValue() >= dlmd.getFromMoney()
                                            .doubleValue()) {

                                            BigDecimal _money = BigDecimal.ZERO;
                                            if (realCash.doubleValue() >= dlmd.getToMoney()
                                                .doubleValue()) {
                                                _money = dlmd.getToMoney()
                                                    .subtract(dlmd.getFromMoney());
                                            } else {
                                                _money = realCash.subtract(dlmd.getFromMoney());
                                            }

                                            if (dlmd.getDriverLevelMoneyType()
                                                .equals(DriverLevelMoneyType.guding)) {// 固定
                                                BigDecimal tcMoney = dlmd.getMoney()
                                                    .multiply(
                                                        new BigDecimal((int) (_money.doubleValue()
                                                            / dlmd.getMoneyUnit().doubleValue())));
                                                companyMoney = companyMoney.add(tcMoney);
                                            } else if (dlmd.getDriverLevelMoneyType()
                                                .equals(DriverLevelMoneyType.ticheng)) {// 比例
                                                BigDecimal tcMoney = _money
                                                    .multiply(dlmd.getCommission())
                                                    .divide(new BigDecimal(100));
                                                companyMoney = companyMoney.add(tcMoney);
                                            }
                                        }
                                    }
                                }

                                if (realCash.compareTo(companyMoney) == -1) {
                                    companyMoney = realCash;
                                    money = BigDecimal.ZERO;
                                    memo += "金额不足，公司实际提成" + companyMoney + "元。";
                                } else {
                                    money = realCash.subtract(companyMoney);
                                }

                                BigDecimal xianjin = order.getCashMoney();// 服务人员现有现金
                                BigDecimal yingde = money;// 服务人员应得提成
                                if (yingde.compareTo(BigDecimal.ZERO) == -1) {
                                    yingde = BigDecimal.ZERO;
                                }

                                memo += "客户使用了面值" + couponRuleMoney + "元的优惠劵，并且优惠劵参与提成，";
                                if (xianjin.compareTo(yingde) == -1) {// 服务人员加钱 公司减钱
                                    memo += "服务人员应提成" + yingde + "元，服务人员现有现金" + xianjin + "元，服务人员增加"
                                        + yingde.subtract(xianjin) + "元，相应公司扣取" + yingde
                                        .subtract(xianjin) + "元。";
                                } else {// 服务人员减钱 公司加钱
                                    memo += "服务人员应提成" + yingde + "元，服务人员现有现金" + xianjin + "元，服务人员扣取"
                                        + xianjin.subtract(yingde) + "元，相应公司收入" + xianjin
                                        .subtract(yingde) + "元。";
                                }

                                Company company = companyMapper
                                    .selectByPrimaryKey(driver.getCompanyId());
                                Company orderCompany = companyMapper
                                    .selectByPrimaryKey(order.getCompanyId());

                                FinancialRecord financialRecord = new FinancialRecord();
                                // 生成订单号
                                StringBuilder sb = new StringBuilder();
                                sb.append(OrderNumberConfig.FINANCIAL_TICHENG);// 提成金额
                                sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);// 对象 客户
                                sb.append(format.format(new Date()));// 年月日时间
                                sb.append(OrderNumberConfig
                                    .padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                                financialRecord.setCode(sb.toString());
                                financialRecord.setCompanyId(company.getId());
                                financialRecord.setCompanyName(company.getAbbreviation());
                                financialRecord.setOrderCompanyId(orderCompany.getId());
                                financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                                financialRecord.setMemo(memo);
                                financialRecord.setMoney(xianjin.subtract(yingde));
                                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                                if (StringUtils.isNotBlank(order.getClientName())) {
                                    financialRecord.setWho(order.getClientName());
                                } else {
                                    financialRecord.setWho(order.getClientPhone());
                                }
                                financialRecord.setOrderId(order.getId());
                                financialRecord
                                    .setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                                financialRecordMapper.insertRecord(financialRecord);

                            }

                        } else {
                            if (order.getPayType().compareTo(PayType.cash) == 0) {// 现金

                                String memo =
                                    "订单号【<a target='_blank' href='/order/detail/" + order.getId()
                                        + "'>"
                                        + order.getOrderNumber() + "</a>】收入。";

                                BigDecimal money = BigDecimal.ZERO;
                                BigDecimal companyMoney = BigDecimal.ZERO;
                                if (!CollectionUtils
                                    .isEmpty(moneyTimeDetail.getDriverLevelMoneyDetails())) {

                                    for (DriverLevelMoneyDetail dlmd : moneyTimeDetail
                                        .getDriverLevelMoneyDetails()) {
                                        if (realCash.doubleValue() >= dlmd.getFromMoney()
                                            .doubleValue()) {

                                            BigDecimal _money = BigDecimal.ZERO;
                                            if (realCash.doubleValue() >= dlmd.getToMoney()
                                                .doubleValue()) {
                                                _money = dlmd.getToMoney()
                                                    .subtract(dlmd.getFromMoney());
                                            } else {
                                                _money = realCash.subtract(dlmd.getFromMoney());
                                            }

                                            if (dlmd.getDriverLevelMoneyType()
                                                .equals(DriverLevelMoneyType.guding)) {// 固定

                                                BigDecimal tcMoney = dlmd.getMoney()
                                                    .multiply(
                                                        new BigDecimal((int) (_money.doubleValue()
                                                            / dlmd.getMoneyUnit().doubleValue())));
                                                companyMoney = companyMoney.add(tcMoney);
                                            } else if (dlmd.getDriverLevelMoneyType()
                                                .equals(DriverLevelMoneyType.ticheng)) {// 比例
                                                BigDecimal tcMoney = _money
                                                    .multiply(dlmd.getCommission())
                                                    .divide(new BigDecimal(100));
                                                companyMoney = companyMoney.add(tcMoney);
                                            }
                                        }
                                    }
                                }

                                if (realCash.compareTo(companyMoney) == -1) {
                                    companyMoney = realCash;
                                    money = BigDecimal.ZERO;
                                    memo += "金额不足，公司实际提成" + companyMoney + "元。";
                                } else {
                                    money = realCash.subtract(companyMoney);
                                }

                                if (null != coupon) {
                                    memo += "客户使用了面值" + couponRuleMoney + "元的优惠劵。";
                                }

                                Company company = companyMapper
                                    .selectByPrimaryKey(driver.getCompanyId());
                                Company orderCompany = companyMapper
                                    .selectByPrimaryKey(order.getCompanyId());

                                FinancialRecord financialRecord = new FinancialRecord();
                                // 生成订单号
                                StringBuilder sb = new StringBuilder();
                                sb.append(OrderNumberConfig.FINANCIAL_TICHENG);// 提成金额
                                sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);// 对象 客户
                                sb.append(format.format(new Date()));// 年月日时间
                                sb.append(OrderNumberConfig
                                    .padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                                financialRecord.setCode(sb.toString());
                                financialRecord.setCompanyId(company.getId());
                                financialRecord.setCompanyName(company.getAbbreviation());
                                financialRecord.setOrderCompanyId(orderCompany.getId());
                                financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                                financialRecord.setMemo(memo);
                                financialRecord.setMoney(companyMoney);
                                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                                if (StringUtils.isNotBlank(order.getClientName())) {
                                    financialRecord.setWho(order.getClientName());
                                } else {
                                    financialRecord.setWho(order.getClientPhone());
                                }
                                financialRecord.setOrderId(order.getId());
                                financialRecord
                                    .setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                                financialRecordMapper.insertRecord(financialRecord);

                            } else if (order.getPayType().compareTo(PayType.sign) == 0) {// 签单

                                String memo =
                                    "订单号【<a target='_blank' href='/order/detail/" + order.getId()
                                        + "'>"
                                        + order.getOrderNumber() + "</a>】收入。";

                                BigDecimal money = BigDecimal.ZERO;
                                BigDecimal companyMoney = BigDecimal.ZERO;
                                if (!CollectionUtils
                                    .isEmpty(moneyTimeDetail.getDriverLevelMoneyDetails())) {

                                    for (DriverLevelMoneyDetail dlmd : moneyTimeDetail
                                        .getDriverLevelMoneyDetails()) {
                                        if (realCash.doubleValue() >= dlmd.getFromMoney()
                                            .doubleValue()) {

                                            BigDecimal _money = BigDecimal.ZERO;
                                            if (realCash.doubleValue() >= dlmd.getToMoney()
                                                .doubleValue()) {
                                                _money = dlmd.getToMoney()
                                                    .subtract(dlmd.getFromMoney());
                                            } else {
                                                _money = realCash.subtract(dlmd.getFromMoney());
                                            }

                                            if (dlmd.getDriverLevelMoneyType()
                                                .equals(DriverLevelMoneyType.guding)) {// 固定
                                                BigDecimal tcMoney = dlmd.getMoney()
                                                    .multiply(
                                                        new BigDecimal((int) (_money.doubleValue()
                                                            / dlmd.getMoneyUnit().doubleValue())));
                                                companyMoney = companyMoney.add(tcMoney);
                                            } else if (dlmd.getDriverLevelMoneyType()
                                                .equals(DriverLevelMoneyType.ticheng)) {// 比例
                                                BigDecimal tcMoney = _money
                                                    .multiply(dlmd.getCommission())
                                                    .divide(new BigDecimal(100));
                                                companyMoney = companyMoney.add(tcMoney);
                                            }
                                        }
                                    }
                                }

                                if (realCash.compareTo(companyMoney) == -1) {
                                    companyMoney = realCash;
                                    money = BigDecimal.ZERO;
                                    memo += "金额不足，公司实际提成" + companyMoney + "元。";
                                } else {
                                    money = realCash.subtract(companyMoney);
                                }

                                if (null != coupon) {
                                    memo += "客户使用了面值" + couponRuleMoney + "元的优惠劵。";
                                }

                                Company company = companyMapper
                                    .selectByPrimaryKey(driver.getCompanyId());
                                Company orderCompany = companyMapper
                                    .selectByPrimaryKey(order.getCompanyId());

                                FinancialRecord financialRecord = new FinancialRecord();
                                StringBuilder sb = new StringBuilder();
                                sb.append(OrderNumberConfig.FINANCIAL_ORDER);// 订单金额
                                sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);// 对象 客户
                                sb.append(format.format(new Date()));// 年月日时间
                                sb.append(OrderNumberConfig
                                    .padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                                financialRecord.setCode(sb.toString());
                                financialRecord.setCompanyId(company.getId());
                                financialRecord.setCompanyName(company.getAbbreviation());
                                financialRecord.setOrderCompanyId(orderCompany.getId());
                                financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                                financialRecord.setMemo(memo);
                                financialRecord.setMoney(companyMoney);
                                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                                if (StringUtils.isNotBlank(order.getClientName())) {
                                    financialRecord.setWho(order.getClientName());
                                } else {
                                    financialRecord.setWho(order.getClientPhone());
                                }
                                financialRecord.setOrderId(order.getId());
                                financialRecord
                                    .setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                                financialRecordMapper.insertRecord(financialRecord);

                            } else if (order.getPayType().compareTo(PayType.balance) == 0) {// 余额

                                if (order.getPayTypeDetails()
                                    .equals(PayTypeDetails.balance_cash)) {// 余额+现金

                                    String memo =
                                        "订单号【<a target='_blank' href='/order/detail/" + order
                                            .getId() + "'>"
                                            + order.getOrderNumber() + "</a>】收入。";

                                    BigDecimal money = BigDecimal.ZERO;
                                    BigDecimal companyMoney = BigDecimal.ZERO;
                                    if (!CollectionUtils
                                        .isEmpty(moneyTimeDetail.getDriverLevelMoneyDetails())) {

                                        for (DriverLevelMoneyDetail dlmd : moneyTimeDetail
                                            .getDriverLevelMoneyDetails()) {
                                            if (realCash.doubleValue() >= dlmd.getFromMoney()
                                                .doubleValue()) {

                                                BigDecimal _money = BigDecimal.ZERO;
                                                if (realCash.doubleValue() >= dlmd.getToMoney()
                                                    .doubleValue()) {
                                                    _money = dlmd.getToMoney()
                                                        .subtract(dlmd.getFromMoney());
                                                } else {
                                                    _money = realCash.subtract(dlmd.getFromMoney());
                                                }

                                                if (dlmd.getDriverLevelMoneyType()
                                                    .equals(DriverLevelMoneyType.guding)) {// 固定
                                                    BigDecimal tcMoney = dlmd.getMoney()
                                                        .multiply(new BigDecimal(
                                                            (int) (_money.doubleValue()
                                                                / dlmd.getMoneyUnit()
                                                                .doubleValue())));
                                                    companyMoney = companyMoney.add(tcMoney);
                                                } else if (dlmd.getDriverLevelMoneyType()
                                                    .equals(DriverLevelMoneyType.ticheng)) {// 比例
                                                    BigDecimal tcMoney = _money
                                                        .multiply(dlmd.getCommission())
                                                        .divide(new BigDecimal(100));
                                                    companyMoney = companyMoney.add(tcMoney);
                                                }
                                            }
                                        }
                                    }

                                    if (realCash.compareTo(companyMoney) == -1) {
                                        companyMoney = realCash;
                                        money = BigDecimal.ZERO;
                                        memo += "金额不足，公司实际提成" + companyMoney + "元。";
                                    } else {
                                        money = realCash.subtract(companyMoney);
                                    }

                                    Company company = companyMapper
                                        .selectByPrimaryKey(driver.getCompanyId());
                                    Company orderCompany = companyMapper
                                        .selectByPrimaryKey(order.getCompanyId());

                                    FinancialRecord financialRecord = new FinancialRecord();
                                    StringBuilder sb = new StringBuilder();
                                    sb.append(OrderNumberConfig.FINANCIAL_ORDER);// 订单金额
                                    sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);// 对象 客户
                                    sb.append(format.format(new Date()));// 年月日时间
                                    sb.append(OrderNumberConfig.padZero(
                                        financialRecordMapper.getRunningNumber() + 1));// 流水号
                                    financialRecord.setCode(sb.toString());
                                    financialRecord.setCompanyId(company.getId());
                                    financialRecord.setCompanyName(company.getAbbreviation());
                                    financialRecord.setOrderCompanyId(orderCompany.getId());
                                    financialRecord
                                        .setOrderCompanyName(orderCompany.getAbbreviation());
                                    financialRecord.setMemo(memo);
                                    financialRecord.setMoney(companyMoney);
                                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                                    if (StringUtils.isNotBlank(order.getClientName())) {
                                        financialRecord.setWho(order.getClientName());
                                    } else {
                                        financialRecord.setWho(order.getClientPhone());
                                    }
                                    financialRecord.setOrderId(order.getId());
                                    financialRecord
                                        .setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                                    financialRecordMapper.insertRecord(financialRecord);

                                } else {
                                    String memo =
                                        "订单号【<a target='_blank' href='/order/detail/" + order
                                            .getId() + "'>"
                                            + order.getOrderNumber() + "</a>】收入。";

                                    BigDecimal money = BigDecimal.ZERO;
                                    BigDecimal companyMoney = BigDecimal.ZERO;
                                    if (!CollectionUtils
                                        .isEmpty(moneyTimeDetail.getDriverLevelMoneyDetails())) {

                                        for (DriverLevelMoneyDetail dlmd : moneyTimeDetail
                                            .getDriverLevelMoneyDetails()) {
                                            if (realCash.doubleValue() >= dlmd.getFromMoney()
                                                .doubleValue()) {

                                                BigDecimal _money = BigDecimal.ZERO;
                                                if (realCash.doubleValue() >= dlmd.getToMoney()
                                                    .doubleValue()) {
                                                    _money = dlmd.getToMoney()
                                                        .subtract(dlmd.getFromMoney());
                                                } else {
                                                    _money = realCash.subtract(dlmd.getFromMoney());
                                                }

                                                if (dlmd.getDriverLevelMoneyType()
                                                    .equals(DriverLevelMoneyType.guding)) {// 固定
                                                    BigDecimal tcMoney = dlmd.getMoney()
                                                        .multiply(new BigDecimal(
                                                            (int) (_money.doubleValue()
                                                                / dlmd.getMoneyUnit()
                                                                .doubleValue())));
                                                    companyMoney = companyMoney.add(tcMoney);
                                                } else if (dlmd.getDriverLevelMoneyType()
                                                    .equals(DriverLevelMoneyType.ticheng)) {// 比例
                                                    BigDecimal tcMoney = _money
                                                        .multiply(dlmd.getCommission())
                                                        .divide(new BigDecimal(100));
                                                    companyMoney = companyMoney.add(tcMoney);
                                                }
                                            }
                                        }
                                    }

                                    if (realCash.compareTo(companyMoney) == -1) {
                                        companyMoney = realCash;
                                        money = BigDecimal.ZERO;
                                        memo += "金额不足，公司实际提成" + companyMoney + "元。";
                                    } else {
                                        money = realCash.subtract(companyMoney);
                                    }

                                    if (null != coupon) {
                                        memo += "客户使用了面值" + couponRuleMoney + "元的优惠劵。";
                                    }

                                    Company company = companyMapper
                                        .selectByPrimaryKey(driver.getCompanyId());
                                    Company orderCompany = companyMapper
                                        .selectByPrimaryKey(order.getCompanyId());

                                    FinancialRecord financialRecord = new FinancialRecord();
                                    StringBuilder sb = new StringBuilder();
                                    sb.append(OrderNumberConfig.FINANCIAL_ORDER);// 订单金额
                                    sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);// 对象 客户
                                    sb.append(format.format(new Date()));// 年月日时间
                                    sb.append(OrderNumberConfig.padZero(
                                        financialRecordMapper.getRunningNumber() + 1));// 流水号
                                    financialRecord.setCode(sb.toString());
                                    financialRecord.setCompanyId(company.getId());
                                    financialRecord.setCompanyName(company.getAbbreviation());
                                    financialRecord.setOrderCompanyId(orderCompany.getId());
                                    financialRecord
                                        .setOrderCompanyName(orderCompany.getAbbreviation());
                                    financialRecord.setMemo(memo);
                                    financialRecord.setMoney(companyMoney);
                                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                                    if (StringUtils.isNotBlank(order.getClientName())) {
                                        financialRecord.setWho(order.getClientName());
                                    } else {
                                        financialRecord.setWho(order.getClientPhone());
                                    }
                                    financialRecord.setOrderId(order.getId());
                                    financialRecord
                                        .setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                                    financialRecordMapper.insertRecord(financialRecord);
                                }
                            }

                        }

                    } else {
                        companyGetAll = true;
                    }
                } else {
                    companyGetAll = true;
                }
            } else {
                companyGetAll = true;
            }

            // 公司得全部
            if (companyGetAll) {
                String memo = "订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                    + order.getOrderNumber() + "</a>】收入。";

                if (null != coupon) {
                    memo += "客户使用了面值" + couponRuleMoney + "元的优惠劵。";
                }

                Company company = companyMapper.selectByPrimaryKey(driver.getCompanyId());
                Company orderCompany = companyMapper.selectByPrimaryKey(order.getCompanyId());

                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb = new StringBuilder();
                sb.append(OrderNumberConfig.FINANCIAL_ORDER);// 订单金额
                sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);// 对象 客户
                sb.append(format.format(new Date()));// 年月日时间
                sb.append(
                    OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                financialRecord.setCode(sb.toString());
                financialRecord.setCompanyId(company.getId());
                financialRecord.setCompanyName(company.getAbbreviation());
                financialRecord.setOrderCompanyId(orderCompany.getId());
                financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                financialRecord.setMemo(memo);
                financialRecord.setMoney(shouruMoney);
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                if (StringUtils.isNotBlank(order.getClientName())) {
                    financialRecord.setWho(order.getClientName());
                } else {
                    financialRecord.setWho(order.getClientPhone());
                }
                financialRecord.setOrderId(order.getId());
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                financialRecordMapper.insertRecord(financialRecord);
            }

        }
        // 醉无忧 - 人保新加
        if (null != order.getOrderNoRenBao() && null != order.getCuponNoRenBao()) {
            zWYApi.syncOrderInfo(order.getOrderNoRenBao(), order.getCuponNoRenBao(),
                order.getOrderNumber(),
                String.valueOf(5), order.getClientPhone());
        }
        return order;
    }

    @Override
    public long counByStatusAndFinishTime(Integer status, Date begin, Date end) {
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        if (null == status) {
            if (principal.isCompanyType()) {
                return orderMapper.countByCompanyWithStatusAndDate(null, null, null, begin, end);
            } else {
                return orderMapper
                    .countByCompanyWithStatusAndDate(principal.getCompanyId(), null, null, begin,
                        end);
            }
        } else {
            if (principal.isCompanyType()) {
                return orderMapper.countByCompanyWithStatusAndDate(null, status, null, begin, end);
            } else {
                return orderMapper
                    .countByCompanyWithStatusAndDate(principal.getCompanyId(), status, null, begin,
                        end);
            }
        }
    }

    @Override
    public List<Order> findByDriverAndStatus(Driver driver, Integer status) {

        return orderMapper.selectByDriverWithStatus(driver.getId(), status, null);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean report(Driver driver, String xml) {

        Document doc = null;

        try {

            doc = DocumentHelper.parseText(xml);

        } catch (DocumentException e) {

            return false;
        }

        Element root = doc.getRootElement();

        @SuppressWarnings("unchecked")
        List<Element> elements = root.elements("order");

        if (!CollectionUtils.isEmpty(elements)) {

            for (Element element : elements) {
                String id = element.attributeValue("id");
                if (NumberUtils.isNumber(id)) {

                    Long orderID = Long.parseLong(id);

                    Order order = orderMapper.selectByPrimaryKey(orderID);
                    Company company = companyMapper.selectByPrimaryKey(order.getCompanyId());
                    Company orderCompany = companyMapper.selectByPrimaryKey(order.getCompanyId());

                    if (order.getStatus() == 6) {
                        continue;
                    }

                    if (Order.ORDER_STATUS_FINISHED != order.getStatus()) {
                        return false;
                    }

                    // 解析xml节点与报销费用
                    OrderOrbit orbit = new OrderOrbit();
                    orbit.setOrderId(order.getId());
                    orbit.setXml(element.element("locations").asXML());
                    orderOrbitMapper.insertRecord(orbit);

                    Element reimbursement = element.element("reimbursement");

                    String memo = reimbursement.element("value").getText();
                    if (null == memo) {
                        memo = StringUtils.EMPTY;
                    }

                    String temp = reimbursement.attributeValue("money");
                    double money = 0.0;
                    if (StringUtils.isNotBlank(temp)) {
                        money = Double.parseDouble(temp.trim());

                        if (money != 0) {
                            // 财务记录（服务人员报销）
                            DateFormat format = new SimpleDateFormat("yyyyMMdd");
                            FinancialRecord financialRecord = new FinancialRecord();
                            StringBuilder sb = new StringBuilder();
                            sb.append(OrderNumberConfig.FINANCIAL_BAOXIAO);// 报销金额
                            sb.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                            sb.append(format.format(new Date()));// 年月日时间
                            sb.append(OrderNumberConfig
                                .padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                            financialRecord.setCode(sb.toString());
                            financialRecord.setCompanyId(company.getId());
                            financialRecord.setCompanyName(company.getAbbreviation());
                            financialRecord.setOrderCompanyId(orderCompany.getId());
                            financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                            financialRecord.setMemo(
                                "订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                                    + order.getOrderNumber() + "</a>】,服务人员【" + driver.getRealname()
                                    + "】报销：" + memo);
                            financialRecord.setMoney(new BigDecimal(-money));
                            financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_WAIT);
                            financialRecord.setWho(driver.getRealname());
                            financialRecord.setOrderId(order.getId());
                            financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_BAOXIAO);
                            financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                            financialRecordMapper.insertRecord(financialRecord);
                        }
                    }

                    Reimbursement re = new Reimbursement();
                    re.setOrderID(order.getId());
                    re.setOrderNum(order.getOrderNumber());
                    re.setDriverID(driver.getId());
                    re.setDriverName(driver.getRealname());
                    re.setMoney(money);
                    re.setMemo(memo);
                    reimbursementMapper.insertRecord(re);

                    order.setStatus(Order.ORDER_STATUS_BAODAN);
                    order.setBaoxiaoCash(new BigDecimal(money));
                    order.setBaoxiaoMemo(memo);
                    orderMapper.updateByPrimaryKey(order);

                    // 添加一条订单状态
                    OrderStatus os = new OrderStatus();
                    os.setOrderId(order.getId());
                    os.setStatusType(StatusType.baodan);
                    os.setContent("【" + driver.getRealname() + "】报单");
                    os.setHappened(new Date());
                    orderStatusMapper.insertRecord(os);

                }

            }

        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean reportV3(Order order, String xml) {

        orderMapper.updateByPrimaryKey(order);

        if (StringUtils.isNotBlank(xml)) {
            Document doc = null;

            try {

                doc = DocumentHelper.parseText(xml);

            } catch (DocumentException e) {

                return false;
            }

            Element root = doc.getRootElement();

            @SuppressWarnings("unchecked")
            List<Element> elements = root.elements("order");

            if (!CollectionUtils.isEmpty(elements)) {

                for (Element element : elements) {
                    // 解析xml节点与报销费用
                    OrderOrbit orbit = new OrderOrbit();
                    orbit.setOrderId(order.getId());
                    orbit.setXml(element.element("locations").asXML());
                    orderOrbitMapper.insertRecord(orbit);

                    Element reimbursement = element.element("reimbursement");

                    String memo = reimbursement.element("value").getText();
                    if (null == memo) {
                        memo = StringUtils.EMPTY;
                    }

                    double money = 0.0;

                    Reimbursement re = new Reimbursement();
                    re.setOrderID(order.getId());
                    re.setOrderNum(order.getOrderNumber());
                    re.setDriverID(order.getDriverId());
                    re.setDriverName(order.getDriverRealName());
                    re.setMoney(money);
                    re.setMemo(memo);
                    reimbursementMapper.insertRecord(re);
                }

            }
        }

        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Order> confirmTaskV4(Order order, Driver driver) {

        Result<Order> result = new Result<Order>();

        driverMapper
            .updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null, driver.getId());

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Order> fillOrderV2(Order order, Long driverID) {

        Result<Order> result = new Result<Order>();

        Driver driver = driverMapper.selectByPrimaryKey(driverID);

        Double longitude = order.getClientLongitude();
        Double latitude = order.getClientLatitude();

        // 根据客户电话查询客户
        Result<Passenger> result_p = passengerApi
            .findOnePassengerByPhone(order.getClientPhone(), settingUtils.get());
        Passenger passenger = result_p.getResult();
        if (null != passenger) {
            // 老客户 更新位置
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            if (!StringUtils.isBlank(order.getClientName()) && StringUtils
                .isBlank(passenger.getName())) {
                passenger.setName(order.getClientName());
                passengerApi.updatePersonal(passenger, settingUtils.get());
            }
        } else {
            // 新客户
            passenger = new Passenger();
            passenger.setName(order.getClientName());
            passenger.setPhone(order.getClientPhone());
            passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_BUDAN);
            passenger.setType(Passenger.TYPE_PASSENGER);
            passenger.setAllowOverdraw(false);
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            Company company = companyMapper.selectByPrimaryKey(driver.getCompanyId());
            passenger.setCompanyId(company.getId());
            passenger.setCompanyName(company.getAbbreviation());

            Result<Passenger> result_p2 = passengerApi
                .createPersonal(passenger, settingUtils.get());
            if (result_p2.isSuccess()) {
                passenger = result_p2.getResult();
            } else {
                result.setMessage(result_p2.getMessage());
                result.setSuccess(false);
                return result;
            }
        }

        DateFormat format = new SimpleDateFormat("yyyyMMdd");

        order.setClientId(passenger.getId());

        if (StringUtils.isBlank(order.getClientName())) {
            order.setClientName(passenger.getName());
        }
        order.setStatus(Order.ORDER_STATUS_BUSY);
        order.setFromSource(Order.ORDER_TYPE_BUDAN);
        order.setOrderType(Order.ORDER_TYPE_BUDAN);
        if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
            order.setMemberType(Order.ORDER_MEMBER_TYPE_PASSENGER);
        } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
            order.setMemberType(Order.ORDER_MEMBER_TYPE_ENTERPRISE);
        }
        order.setCompanyId(driver.getCompanyId());
        order.setDriverId(driver.getId());
        order.setDriverName(driver.getName());
        order.setDriverRealName(driver.getRealname());
        order.setDriverPhone(driver.getPhone());

        if (passenger.isInBlackList()) {
            order.setMemo("黑名单客户");
        }

        // 生成订单号
        StringBuilder sb = new StringBuilder();

        if (Driver.DEVICE_ANDRIOD.equals(driver.getDeviceType())) {
            sb.append(OrderNumberConfig.FROMANDROID);// android
        } else if (Driver.DEVICE_IOS.equals(driver.getDeviceType())) {
            sb.append(OrderNumberConfig.FROMIOS);// ios
        } else {
            sb.append(OrderNumberConfig.FROMANDROID);// android
        }

        if (null != passenger && passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
            sb.append(OrderNumberConfig.COMPANY);// 企业用户
        } else {
            sb.append(OrderNumberConfig.CUSTOMER);// 普通用户
        }

        sb.append(format.format(new Date()));// 年月日时间
        sb.append(OrderNumberConfig.padZero(orderMapper.getRunningNumber() + 1));// 流水号
        order.setOrderNumber(sb.toString());

        orderMapper.insertRecord(order);

        // 设置服务人员为忙碌
        driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_BUSY,
            Driver.DRIVER_JOBSTATUS_DAIJIA,
            driver.getId());
        driver.setStatus(Driver.DRIVER_BUSY);

        // 扣费
        Company company = companyMapper.selectByPrimaryKey(order.getCompanyId());
        if (null != company.getInfoFeeType()
            && company.getInfoFeeType().compareTo(Company.InfoFeeType.acceptTask) == 0) {
            if (company.getInfoFee().doubleValue() != 0) {
                driver.setVirtual(driver.getVirtual().subtract(company.getInfoFee()));
                driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                // 扣费记录
                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                driverPaymentsRecord.setMoney(company.getInfoFee());
                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                driverPaymentsRecord.setInfoFeeType(DriverPaymentsRecord.INFOFEE_TYPE_INFO);
                driverPaymentsRecord.setDriverId(driver.getId());
                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                driverPaymentsRecord.setOrderId(order.getId());
                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                driverPaymentsRecord.setMemo("扣除公司所得信息费" + company.getInfoFee() + "元。");
                driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                driverPaymentsRecord.setHappend(new Date());
                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                // 财务记录（保险费/信息费）
                Company mainCompany = companyMapper.selectMainCompany();
                DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb_f = new StringBuilder();
                sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 保险费/信息费
                sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                sb_f.append(format_f.format(new Date()));// 年月日时间
                sb_f.append(
                    OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                financialRecord.setCode(sb_f.toString());
                financialRecord.setCompanyId(mainCompany.getId());
                financialRecord.setCompanyName(mainCompany.getAbbreviation());
                financialRecord.setOrderCompanyId(mainCompany.getId());
                financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                financialRecord
                    .setMemo("订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                        + order.getOrderNumber() + "</a>】信息费");
                financialRecord.setMoney(company.getInfoFee());
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                financialRecord.setWho(driver.getRealname());
                financialRecord.setOrderId(order.getId());
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                financialRecordMapper.insertRecord(financialRecord);
            }
        }

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.budan);
        os.setContent("【" + driver.getRealname() + "】补单");
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        OrderStatus os2 = new OrderStatus();
        os2.setOrderId(order.getId());
        os2.setStatusType(StatusType.accept);
        os2.setContent("【" + driver.getRealname() + "】接受订单");
        os2.setHappened(new Date());
        orderStatusMapper.insertRecord(os2);

        result.setSuccess(true);
        return result;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Order> fillOrderV4(Order order, Long driverID) {

        Result<Order> result = new Result<Order>();

        Driver driver = driverMapper.selectByPrimaryKey(driverID);

        Double longitude = order.getClientLongitude();
        Double latitude = order.getClientLatitude();

        // 根据客户电话查询客户
        Result<Passenger> result_p = passengerApi
            .findOnePassengerByPhone(order.getClientPhone(), settingUtils.get());
        Passenger passenger = result_p.getResult();
        if (null != passenger) {
            // 老客户 更新位置
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            if (!StringUtils.isBlank(order.getClientName()) && StringUtils
                .isBlank(passenger.getName())) {
                passenger.setName(order.getClientName());
                passengerApi.updatePersonal(passenger, settingUtils.get());
            }
        } else {
            // 新客户
            passenger = new Passenger();
            passenger.setName(order.getClientName());
            passenger.setPhone(order.getClientPhone());
            passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_BUDAN);
            passenger.setType(Passenger.TYPE_PASSENGER);
            passenger.setAllowOverdraw(false);
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            Company company = companyMapper.selectByPrimaryKey(driver.getCompanyId());
            passenger.setCompanyId(company.getId());
            passenger.setCompanyName(company.getAbbreviation());

            Result<Passenger> result_p2 = passengerApi
                .createPersonal(passenger, settingUtils.get());
            if (result_p2.isSuccess()) {
                passenger = result_p2.getResult();
            } else {
                result.setMessage(result_p2.getMessage());
                result.setSuccess(false);
                return result;
            }
        }

        DateFormat format = new SimpleDateFormat("yyyyMMdd");

        order.setClientId(passenger.getId());

        if (StringUtils.isBlank(order.getClientName())) {
            order.setClientName(passenger.getName());
        }
        order.setStatus(Order.ORDER_STATUS_BUSY);
        order.setFromSource(Order.ORDER_TYPE_BUDAN);
        order.setOrderType(Order.ORDER_TYPE_BUDAN);
        if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
            order.setMemberType(Order.ORDER_MEMBER_TYPE_PASSENGER);
        } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
            order.setMemberType(Order.ORDER_MEMBER_TYPE_ENTERPRISE);
        }
        order.setCompanyId(driver.getCompanyId());
        order.setDriverId(driver.getId());
        order.setDriverName(driver.getName());
        order.setDriverRealName(driver.getRealname());
        order.setDriverPhone(driver.getPhone());

        if (passenger.isInBlackList()) {
            order.setMemo("黑名单客户");
        }

        // 生成订单号
        StringBuilder sb = new StringBuilder();

        if (Driver.DEVICE_ANDRIOD.equals(driver.getDeviceType())) {
            sb.append(OrderNumberConfig.FROMANDROID);// android
        } else if (Driver.DEVICE_IOS.equals(driver.getDeviceType())) {
            sb.append(OrderNumberConfig.FROMIOS);// ios
        } else {
            sb.append(OrderNumberConfig.FROMANDROID);// android
        }

        if (null != passenger && passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
            sb.append(OrderNumberConfig.COMPANY);// 企业用户
        } else {
            sb.append(OrderNumberConfig.CUSTOMER);// 普通用户
        }

        sb.append(format.format(new Date()));// 年月日时间
        sb.append(OrderNumberConfig.padZero(orderMapper.getRunningNumber() + 1));// 流水号
        order.setOrderNumber(sb.toString());

        order.setArrivePlaceDate(new Date());
        order.setStartDriveDate(new Date());

        orderMapper.insertRecord(order);

        // 设置服务人员为忙碌
        driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_BUSY,
            Driver.DRIVER_JOBSTATUS_DAIJIA,
            driver.getId());
        driver.setStatus(Driver.DRIVER_BUSY);

        // 扣费
        Company company = companyMapper.selectByPrimaryKey(order.getCompanyId());
        if (null != company.getInfoFeeType()
            && company.getInfoFeeType().compareTo(Company.InfoFeeType.acceptTask) == 0) {
            if (company.getInfoFee().doubleValue() != 0) {
                driver.setVirtual(driver.getVirtual().subtract(company.getInfoFee()));
                driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                // 扣费记录
                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                driverPaymentsRecord.setMoney(company.getInfoFee());
                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                driverPaymentsRecord.setInfoFeeType(DriverPaymentsRecord.INFOFEE_TYPE_INFO);
                driverPaymentsRecord.setDriverId(driver.getId());
                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                driverPaymentsRecord.setOrderId(order.getId());
                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                driverPaymentsRecord.setMemo("扣除公司所得信息费" + company.getInfoFee() + "元。");
                driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                driverPaymentsRecord.setHappend(new Date());
                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                // 财务记录（保险费/信息费）
                Company mainCompany = companyMapper.selectMainCompany();
                DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb_f = new StringBuilder();
                sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 保险费/信息费
                sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                sb_f.append(format_f.format(new Date()));// 年月日时间
                sb_f.append(
                    OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                financialRecord.setCode(sb_f.toString());
                financialRecord.setCompanyId(mainCompany.getId());
                financialRecord.setCompanyName(mainCompany.getAbbreviation());
                financialRecord.setOrderCompanyId(mainCompany.getId());
                financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                financialRecord
                    .setMemo("订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                        + order.getOrderNumber() + "</a>】信息费");
                financialRecord.setMoney(company.getInfoFee());
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                financialRecord.setWho(driver.getRealname());
                financialRecord.setOrderId(order.getId());
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                financialRecordMapper.insertRecord(financialRecord);
            }
            // 代驾险
            if (null != order.getDjxFee() && order.getDjxFee().doubleValue() != 0) {
                driver.setVirtual(driver.getVirtual().subtract(order.getDjxFee()));
                driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                // 扣费记录
                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                driverPaymentsRecord.setMoney(order.getDjxFee());
                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                driverPaymentsRecord.setInfoFeeType(DriverPaymentsRecord.INFOFEE_TYPE_DJX);
                driverPaymentsRecord.setDriverId(driver.getId());
                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                driverPaymentsRecord.setOrderId(order.getId());
                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                driverPaymentsRecord.setMemo("扣除公司所得代驾险" + order.getDjxFee() + "元。");
                driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                driverPaymentsRecord.setHappend(new Date());
                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                // 财务记录（保险费）
                Company mainCompany = companyMapper.selectMainCompany();
                DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb_f = new StringBuilder();
                sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 保险费
                sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                sb_f.append(format_f.format(new Date()));// 年月日时间
                sb_f.append(
                    OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                financialRecord.setCode(sb_f.toString());
                financialRecord.setCompanyId(mainCompany.getId());
                financialRecord.setCompanyName(mainCompany.getAbbreviation());
                financialRecord.setOrderCompanyId(mainCompany.getId());
                financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                financialRecord
                    .setMemo("订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                        + order.getOrderNumber() + "</a>】代驾险");
                financialRecord.setMoney(order.getDjxFee());
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                financialRecord.setWho(driver.getRealname());
                financialRecord.setOrderId(order.getId());
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                financialRecordMapper.insertRecord(financialRecord);

                // 保险记录
                DjInsurance djInsurance = new DjInsurance();
                djInsurance.setInsuranceType(DjInsurance.InsuranceType.djx);
                djInsurance.setMoney(order.getDjxFee());
                djInsurance.setOrderId(order.getId());
                djInsurance.setOrderNo(order.getOrderNumber());
                djInsuranceMapper.insertRecord(djInsurance);

                DjxNoticeEvent djxNoticeEvent = new DjxNoticeEvent(driver, djInsurance);
                applicationEventMulticaster.multicastEvent(djxNoticeEvent);
            }
            // 意外险
            if (null != order.getYwxFee() && order.getYwxFee().doubleValue() != 0) {
                driver.setVirtual(driver.getVirtual().subtract(order.getYwxFee()));
                driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                // 扣费记录
                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                driverPaymentsRecord.setMoney(order.getYwxFee());
                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                driverPaymentsRecord.setInfoFeeType(DriverPaymentsRecord.INFOFEE_TYPE_YWX);
                driverPaymentsRecord.setDriverId(driver.getId());
                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                driverPaymentsRecord.setOrderId(order.getId());
                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                driverPaymentsRecord.setMemo("扣除公司所得意外险" + order.getYwxFee() + "元。");
                driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                driverPaymentsRecord.setHappend(new Date());
                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                // 财务记录（保险费）
                Company mainCompany = companyMapper.selectMainCompany();
                DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb_f = new StringBuilder();
                sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 保险费
                sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                sb_f.append(format_f.format(new Date()));// 年月日时间
                sb_f.append(
                    OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                financialRecord.setCode(sb_f.toString());
                financialRecord.setCompanyId(mainCompany.getId());
                financialRecord.setCompanyName(mainCompany.getAbbreviation());
                financialRecord.setOrderCompanyId(mainCompany.getId());
                financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                financialRecord
                    .setMemo("订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                        + order.getOrderNumber() + "</a>】意外险");
                financialRecord.setMoney(order.getYwxFee());
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                financialRecord.setWho(driver.getRealname());
                financialRecord.setOrderId(order.getId());
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                financialRecordMapper.insertRecord(financialRecord);

                // 保险记录
                DjInsurance djInsurance = new DjInsurance();
                djInsurance.setInsuranceType(DjInsurance.InsuranceType.ywx);
                djInsurance.setMoney(order.getYwxFee());
                djInsurance.setOrderId(order.getId());
                djInsurance.setOrderNo(order.getOrderNumber());
                djInsuranceMapper.insertRecord(djInsurance);

                YwxNoticeEvent ywxNoticeEvent = new YwxNoticeEvent(driver, djInsurance);
                applicationEventMulticaster.multicastEvent(ywxNoticeEvent);
            }
        }

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.budan);
        os.setContent("【" + driver.getRealname() + "】补单");
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        OrderStatus os2 = new OrderStatus();
        os2.setOrderId(order.getId());
        os2.setStatusType(StatusType.accept);
        os2.setContent("【" + driver.getRealname() + "】接受订单");
        os2.setHappened(new Date());
        orderStatusMapper.insertRecord(os2);

        OrderStatus os3 = new OrderStatus();
        os3.setOrderId(order.getId());
        os3.setStatusType(StatusType.daokehu);
        os3.setContent("【" + driver.getRealname() + "】到达客户所在地，开始等待");
        os3.setHappened(new Date());
        orderStatusMapper.insertRecord(os3);

        OrderStatus os4 = new OrderStatus();
        os4.setOrderId(order.getId());
        os4.setStatusType(StatusType.daijia2);
        os4.setContent("【" + driver.getRealname() + "】出发前往客户目的地，等待客户时间为：" + 0 + "分钟");
        os4.setHappened(new Date());
        orderStatusMapper.insertRecord(os4);

        result.setSuccess(true);
        return result;

    }

    // 一键下单
    @Transactional(rollbackFor = Exception.class)
    public List<Order> orderAppointment(Order order, Integer driverNum, Double longitude,
        Double latitude,
        String acKey) {

        // 根据客户电话查询客户

        Result<Passenger> result_p = passengerApi
            .findOnePassengerByPhone(order.getClientPhone(), settingUtils.get());
        Passenger passenger = result_p.getResult();

        Company appointCompany = null;
        if (StringUtils.isNotBlank(acKey)) {
            appointCompany = companyMapper.selectByAppKey(acKey);
        }
        Company company = null;

        if (null != appointCompany) {
            company = appointCompany;
        } else {
            if (null != passenger) {
                String city = "";
                try {
                    city = HttpClientUtil.getCityByLngAndLat(longitude, latitude);
                } catch (Exception e) {
                }

                if (StringUtils.isNotBlank(city)) {

                    List<Company> pipeiCompanys = companyMapper.selectByAreaCityName(city);

                    if (!CollectionUtils.isEmpty(pipeiCompanys)) {

                        for (Company c : pipeiCompanys) {
                            if (c.getId().equals(passenger.getCompanyId())) {
                                company = c;
                                break;
                            }
                        }

                        List<Company> notMainCompanys = new ArrayList<Company>();// 子公司

                        if (null == company) {
                            for (Company c : pipeiCompanys) {
                                if (!c.isCompanyType()) {
                                    if (StringUtils.isBlank(c.getAppKey())) {
                                        notMainCompanys.add(c);
                                    }
                                }
                            }
                            if (!CollectionUtils.isEmpty(notMainCompanys)) {
                                company = notMainCompanys
                                    .get(new Random().nextInt(notMainCompanys.size()));
                            }
                        }
                    }
                }
            }
        }

        if (null != passenger) {
            // 老客户 更新位置
            passengerApi
                .updatePassengerFromPlace(passenger.getId(), order.getFromPlace(), longitude,
                    latitude,
                    settingUtils.get());
            // memberMapper.updatePosByPrimaryKey(longitude, latitude,
            // passenger.getId());
            if (null == company) {
                company = companyMapper.selectByPrimaryKey(passenger.getCompanyId());
            }
        } else {
            // 新客户
            passenger = new Passenger();
            passenger.setName(order.getClientName());
            passenger.setPhone(order.getClientPhone());
            passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_APP);
            passenger.setType(Passenger.TYPE_PASSENGER);
            passenger.setAllowOverdraw(false);
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);

            if (null != company) {
                passenger.setCompanyId(company.getId());
                passenger.setCompanyName(company.getAbbreviation());
            } else {
                company = companyMapper.selectMainCompany();
                passenger.setCompanyId(company.getId());
                passenger.setCompanyName(company.getAbbreviation());
            }
            Result<Passenger> result = passengerApi.createPersonal(passenger, settingUtils.get());
            if (result.isSuccess()) {
                passenger = result.getResult();
            }
        }

        DateFormat format = new SimpleDateFormat("yyyyMMdd");

        order.setClientLongitude(longitude);
        order.setClientLatitude(latitude);
        order.setClientId(passenger.getId());
        order.setClientName(passenger.getName());

        if (passenger.isInBlackList()) {
            if (StringUtils.isBlank(order.getMemo())) {
                order.setMemo("黑名单客户");
            } else {
                order.setMemo(order.getMemo() + ";" + "黑名单客户");
            }
        }

        List<Order> newOrders = new ArrayList<Order>();

        // 生成订单号
        StringBuilder sb = new StringBuilder();

        sb.append(OrderNumberConfig.FROMCUSTOMER);// 客户端
        if (null != passenger && passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
            sb.append(OrderNumberConfig.COMPANY);// 企业用户
        } else {
            sb.append(OrderNumberConfig.CUSTOMER);// 普通用户
        }
        sb.append(format.format(new Date()));// 年月日时间
        String sbStr = sb.toString();
        long number = orderMapper.getRunningNumber();

        if (driverNum > 1) {
            OrderGroup orderGroup = new OrderGroup();
            orderGroupMapper.insertRecord(orderGroup);
            order.setOrderGroupId(orderGroup.getId());
            if (StringUtils.isBlank(order.getMemo())) {
                order.setMemo("客户同时预约" + driverNum + "人");
            } else {
                order.setMemo(order.getMemo() + ";" + "客户同时预约" + driverNum + "人");
            }
        }

        for (int i = 1; i <= driverNum; i++) {
            Order dborder = new Order();
            BeanUtils.copyProperties(order, dborder);
            dborder.setStatus(0);
            dborder.setOrderType(Order.ORDER_TYPE_APP);
            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                dborder.setMemberType(Order.ORDER_MEMBER_TYPE_PASSENGER);
            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                dborder.setMemberType(Order.ORDER_MEMBER_TYPE_ENTERPRISE);
            }
            dborder.setCompanyId(company.getId());

            number += 1;
            dborder.setOrderNumber(sbStr + OrderNumberConfig.padZero(number));

            orderMapper.insertRecord(dborder);
            newOrders.add(dborder);

        }

        return newOrders;

    }

    @Override
    public Page<Map<String, Object>> historyOrderV3(String phone, String acKey, Integer page,
        Integer limit) {

        Company appointCompany = null;
        Integer hasDriver = 0;
        if (StringUtils.isNotBlank(acKey)) {
            appointCompany = companyMapper.selectByAppKey(acKey);
        }

        Pageable pageable = new PageRequest(page, limit);

        List<Order> content = new ArrayList<Order>();
        long total = 0;
        if (null != appointCompany) {
            content = orderMapper
                .selectHistoryOrder(phone, appointCompany.getId(), page * limit, limit);
            total = orderMapper.countHistoryOrder(phone, appointCompany.getId());
        } else {
            content = orderMapper.selectHistoryOrder(phone, null, page * limit, limit);
            total = orderMapper.countHistoryOrder(phone, null);
        }

        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(content)) {
            Setting setting = settingUtils.get();
            for (Order order : content) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("orderId", order.getId());
                map.put("orderNumber", order.getOrderNumber());
                map.put("orderBookTime", order.getServerTime());
                map.put("orderCreatedTime", order.getCreated());
                map.put("orderCreatedTimeStr",
                    new SimpleDateFormat("MM/dd HH:mm").format(order.getCreated()));
                map.put("orderBookAddress", order.getFromPlace());
                map.put("hasbeenRate", order.isHasbeenRate());

                String orderStatus = "已完成";
                if (order.getStatus() == 6) {
                    orderStatus = "已报单";
                }

                map.put("orderStatus", orderStatus);
                map.put("orderCarType", order.getOrderCarType());
                map.put("orderTotalCost", order.getRealCash());
                map.put("orderTargetAddress", order.getToPlace());
                map.put("orderIsRate", order.isHasbeenRate());
                map.put("orderDriverId", order.getDriverId());
                map.put("orderDriverName", order.getDriverName());
                if (null != order.getDriverId()) {
                    Driver driver = driverMapper.selectByPrimaryKey(order.getDriverId());
                    if (null != driver) {
                        map.put("orderDriverHead",
                            setting.getWebUrl() + "/upload/driver/" + driver.getPhoto());
                        hasDriver = 1;
                        map.put("hasDriver", hasDriver);
                        if (!setting.isAllowCallDriver()) {
                            Company company = companyMapper
                                .selectByPrimaryKey(order.getCompanyId());
                            map.put("orderDriverPhone", company.getTelephone());
                        } else {
                            map.put("orderDriverPhone", driver.getPhone());
                        }
                        map.put("orderDriverLat", driver.getLatitude());
                        map.put("orderDriverLng", driver.getLongitude());
                        map.put("orderDriverAccept", order.getChufaTime());
                        map.put("orderDriverArrived", order.getDaokehuTime());
                        map.put("orderDriverStar", driver.getStarLevel());
                        map.put("orderDriverTimes", driver.getDriveTimes());
                        map.put("orderDriverJialing", driver.getjialing());
                    }
                }
                mapList.add(map);
            }
        }

        Page<Map<String, Object>> result = new PageImpl<Map<String, Object>>(mapList, pageable,
            total);
        return result;
    }

    @Override
    public Page<Order> todayOrder(String phone, String acKey, Integer page, Integer limit) {

        Company appointCompany = null;
        if (StringUtils.isNotBlank(acKey)) {
            appointCompany = companyMapper.selectByAppKey(acKey);
        }

        Pageable pageable = new PageRequest(page, limit);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());

        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        final Date start = calendar.getTime();

        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        final Date end = calendar.getTime();

        List<Order> content = new ArrayList<Order>();
        long total = 0;

        if (null != appointCompany) {
            content = orderMapper
                .selectTodayOrder(phone, appointCompany.getId(), start, end, page * limit, limit);
            total = orderMapper.countTodayOrder(phone, appointCompany.getId(), start, end);
        } else {
            content = orderMapper.selectTodayOrder(phone, null, start, end, page * limit, limit);
            total = orderMapper.countTodayOrder(phone, null, start, end);
        }

        return new PageImpl<Order>(content, pageable, total);

    }

    @Override
    public List<Order> todayOrder(final String phone) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());

        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        final Date start = calendar.getTime();

        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        final Date end = calendar.getTime();

        List<Order> content = orderMapper.selectTodayOrder(phone, null, start, end, null, null);

        return content;
    }

    @Override
    public long countByStatus(int status) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        if (!principal.isCompanyType()) {
            return orderMapper.countByCompanyWithStatus(principal.getCompanyId(), status, null);
        } else {
            return orderMapper.countByCompanyWithStatus(null, status, null);
        }

    }

    @Override
    public long countByStatus(int status1, int status2) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        if (!principal.isCompanyType()) {
            return orderMapper.countByCompanyWithStatus(principal.getCompanyId(), status1, status2);
        } else {
            return orderMapper.countByCompanyWithStatus(null, status1, status2);
        }

    }

    @Override
    public BigDecimal sumFinishedMoneyByFinishTime(Date begin, Date end) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        if (!principal.isCompanyType()) {
            return orderMapper.sumMoneyByCompanyWithDate(principal.getCompanyId(), begin, end);
        } else {
            return orderMapper.sumMoneyByCompanyWithDate(null, begin, end);
        }

    }

    @Override
    public long countFinishedByFinishTime(Date begin, Date end) {
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        if (!principal.isCompanyType()) {
            return orderMapper.countFinishedByCompanyWithDate(principal.getCompanyId(), begin, end);
        } else {
            return orderMapper.countFinishedByCompanyWithDate(null, begin, end);
        }
    }

    @Override
    public long countFinishedByPassengerAndFinishTime(Long passengerId, String[] orderFromSources,
        Date begin,
        Date end) {

        return orderMapper
            .countFinishedByPassengerWithDate(passengerId, orderFromSources, begin, end);
    }

    // 自主预约
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void customerOrder(Order order, Driver driver, Passenger passenger, String acKey) {

        Company appointCompany = null;
        if (StringUtils.isNotBlank(acKey)) {
            appointCompany = companyMapper.selectByAppKey(acKey);
        }

        Integer driverOldStatus = driver.getStatus();

        Double longitude = order.getClientLongitude();
        Double latitude = order.getClientLatitude();
        String fromPlace = order.getFromPlace();

        passengerApi.updatePassengerFromPlace(passenger.getId(), fromPlace, longitude, latitude,
            settingUtils.get());
        // memberMapper.updatePosByPrimaryKey(longitude,
        // latitude,passenger.getId());

        DateFormat format = new SimpleDateFormat("yyyyMMdd");

        order.setClientId(passenger.getId());

        if (passenger.isInBlackList()) {
            order.setMemo("黑名单客户");
        }

        order.setOrderType(Order.ORDER_TYPE_APP);

        if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
            order.setMemberType(Order.ORDER_MEMBER_TYPE_PASSENGER);
        } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
            order.setMemberType(Order.ORDER_MEMBER_TYPE_ENTERPRISE);
        }

        if (null != appointCompany) {
            order.setCompanyId(appointCompany.getId());
        } else {
            order.setCompanyId(driver.getCompanyId());
        }
        if (driverOldStatus == Driver.DRIVER_ONLINE) {
            order.setStatus(Order.ORDER_STATUS_YIPAIDAN);
            order.setDriverId(driver.getId());
            order.setDriverName(driver.getName());
            order.setDriverRealName(driver.getRealname());
            order.setDriverPhone(driver.getPhone());
        } else {
            if (StringUtils.isBlank(order.getMemo())) {
                order.setMemo("客户自主预约服务人员【" + driver.getRealname() + "】");
            } else {
                order.setMemo(order.getMemo() + ";" + "客户自主预约服务人员【" + driver.getRealname() + "】");
            }
        }

        // 生成订单号
        StringBuilder sb = new StringBuilder();

        sb.append(OrderNumberConfig.FROMCUSTOMER);// 客户端
        if (null != passenger && passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
            sb.append(OrderNumberConfig.COMPANY);// 企业用户
        } else {
            sb.append(OrderNumberConfig.CUSTOMER);// 普通用户
        }
        sb.append(format.format(new Date()));// 年月日时间
        sb.append(OrderNumberConfig.padZero(orderMapper.getRunningNumber() + 1));// 流水号
        order.setOrderNumber(sb.toString());

        orderMapper.insertRecord(order);

        if (driverOldStatus == Driver.DRIVER_ONLINE) {
            // 设置服务人员为接单
            driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_APPLY_ORDER,
                Driver.DRIVER_JOBSTATUS_DAIJIA, driver.getId());
            driver.setStatus(Driver.DRIVER_APPLY_ORDER);

            // 添加一条订单状态
            OrderStatus os = new OrderStatus();
            os.setOrderId(order.getId());
            os.setStatusType(StatusType.paidan);
            os.setContent("【" + passenger.getName() + "】下单给服务人员【" + driver.getRealname() + "】");
            os.setHappened(new Date());
            orderStatusMapper.insertRecord(os);

        }

        // 生成常用服务人员记录
        UsuallyDriver usuallyDriver = usuallyDriverMapper.selectByDriverAndMember(driver.getId(),
            order.getClientPhone());
        if (null != usuallyDriver) {
            usuallyDriver.setDriverTime(usuallyDriver.getDriverTime() + 1);
            usuallyDriverMapper.updateByPrimaryKey(usuallyDriver);
        } else {
            usuallyDriver = new UsuallyDriver();
            usuallyDriver.setDriverTime(1);
            usuallyDriver.setDriver(driver);
            usuallyDriver.setMemberId(passenger.getId());
            usuallyDriver.setPhone(order.getClientPhone());
            usuallyDriverMapper.insertRecord(usuallyDriver);
        }

        if (driverOldStatus == Driver.DRIVER_ONLINE) {
            // 派单事件
            order.setRinging(true);
            OrderPaidanEvent paidanEvent = new OrderPaidanEvent(order);
            applicationEventMulticaster.multicastEvent(paidanEvent);

            OrderRecordEvent orderRecordEvent = new OrderRecordEvent(order);
            applicationEventMulticaster.multicastEvent(orderRecordEvent);
        } else {
            // 新单事件
            OrderCreateEvent event = new OrderCreateEvent(order);
            applicationEventMulticaster.multicastEvent(event);

            OrderRecordEvent orderRecordEvent = new OrderRecordEvent(order);
            applicationEventMulticaster.multicastEvent(orderRecordEvent);
        }

    }

    // @Override
    // public Long countTodayOrderByMember(final Date begin, final Date end,final
    // Long memberid) {
    // return orderDao.count(new Specification<Order>() {
    //
    // public Predicate toPredicate(Root<Order> root, CriteriaQuery<?> query,
    // CriteriaBuilder cb) {
    //
    // Predicate predicate=cb.conjunction();
    //
    // predicate.getExpressions().add(cb.equal(root.get("clientId"), memberid));
    //
    // predicate.getExpressions().add(cb.greaterThanOrEqualTo(root.<Date>get("created"),
    // begin));
    //
    // predicate.getExpressions().add(cb.lessThan(root.<Date>get("created"),
    // end));
    //
    // predicate.getExpressions().add(cb.or(
    // cb.equal(root.get("status"), Order.ORDER_STATUS_YIPAIDAN),
    // cb.equal(root.get("status"), Order.ORDER_STATUS_BUSY)
    // ));
    //
    // return predicate;
    //
    // }
    // });
    // }

    @Override
    public List<Order> findTodayOrderByMember(Date start, Date end, Long clientId) {

        List<Order> list = orderMapper.selectBusyByMemberWithDate(clientId, start, end);

        List<Order> list2 = orderMapper
            .selectByMemberWithStatus(clientId, Order.ORDER_STATUS_NEW, null, null, null,
                null);

        List<Order> newlist = new ArrayList<Order>();

        newlist.addAll(list);
        newlist.addAll(list2);

        return newlist;
    }

    @Override
    public List<Order> listBusyOrders() {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        if (!principal.isCompanyType()) {
            return orderMapper
                .selectByCompanyWithStatus(principal.getCompanyId(), Order.ORDER_STATUS_BUSY, null);
        } else {
            return orderMapper.selectByCompanyWithStatus(null, Order.ORDER_STATUS_BUSY, null);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void arrivePlace(Order order, Date arriveTime) {

        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.daokehu);
        os.setContent("【" + order.getDriverRealName() + "】到达客户所在地，开始等待");
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        // 到达客户所在地事件
        OrderArriveFromPlaceEvent arriveFromPlaceEvent = new OrderArriveFromPlaceEvent(order, true);
        applicationEventMulticaster.multicastEvent(arriveFromPlaceEvent);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void arrivePlaceV4(Order order) {

        if (null == order.getArrivePlaceDate()) {
            order.setArrivePlaceDate(new Date());
            orderMapper.updateByPrimaryKey(order);

            OrderStatus os = new OrderStatus();
            os.setOrderId(order.getId());
            os.setStatusType(StatusType.daokehu);
            os.setContent("【" + order.getDriverRealName() + "】到达客户所在地，开始等待");
            os.setHappened(new Date());
            orderStatusMapper.insertRecord(os);

            // 到达客户所在地事件
            OrderArriveFromPlaceEvent arriveFromPlaceEvent = new OrderArriveFromPlaceEvent(order,
                true);
            applicationEventMulticaster.multicastEvent(arriveFromPlaceEvent);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void startDrive(Order order, Date arriveTime, Date startDriveTime, Driver driver,
        String isWannaWc,
        Long workCarTime, Long areaId) {

        if (null != workCarTime && 0 != workCarTime) {
            order.setFinishTime(new Date(workCarTime));
        }
        orderMapper.updateByPrimaryKey(order);
        driverMapper.updateByPrimaryKey(driver);

        if (null == order.getDaokehuTime()) {
            OrderStatus os = new OrderStatus();
            os.setOrderId(order.getId());
            os.setStatusType(StatusType.daokehu);
            os.setContent("【" + order.getDriverRealName() + "】到达客户所在地，开始等待");
            os.setHappened(new Date());
            orderStatusMapper.insertRecord(os);

            // 到达客户所在地事件
            OrderArriveFromPlaceEvent arriveFromPlaceEvent = new OrderArriveFromPlaceEvent(order,
                false);
            applicationEventMulticaster.multicastEvent(arriveFromPlaceEvent);
        }

        if (null == order.getDaijiaTime2()) {
            Date start = order.getDaokehuTime() == null ? new Date() : order.getDaokehuTime();
            Date end = new Date();
            Long minute = (end.getTime() - start.getTime()) / (1000 * 60);

            OrderStatus os = new OrderStatus();
            os.setOrderId(order.getId());
            os.setStatusType(StatusType.daijia2);
            os.setContent("【" + order.getDriverRealName() + "】出发前往客户目的地，等待客户时间为：" + minute + "分钟");
            os.setHappened(new Date());
            orderStatusMapper.insertRecord(os);

            // 开始代驾事件
            OrderStartDriveEvent startDriveEvent = new OrderStartDriveEvent(order);
            applicationEventMulticaster.multicastEvent(startDriveEvent);
        }

        if (order.getHasToPlace()) {
            // 请求接事件
            OrderQingqiujieEvent qingqiujieEvent = new OrderQingqiujieEvent(order);
            applicationEventMulticaster.multicastEvent(qingqiujieEvent);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void startDriveV4(Order order, Integer waiteTime) {

        if (null == order.getStartDriveDate()) {
            order.setStartDriveDate(new Date());
            orderMapper.updateByPrimaryKey(order);

            OrderStatus os = new OrderStatus();
            os.setOrderId(order.getId());
            os.setStatusType(StatusType.daijia2);
            os.setContent(
                "【" + order.getDriverRealName() + "】出发前往客户目的地，等待客户时间为：" + waiteTime + "分钟");
            os.setHappened(new Date());
            orderStatusMapper.insertRecord(os);

            // 开始代驾事件
            OrderStartDriveEvent startDriveEvent = new OrderStartDriveEvent(order);
            applicationEventMulticaster.multicastEvent(startDriveEvent);
        }

    }

    @Override
    public List<Order> listByStatus(final Integer status) {

        Subject currentUser = SecurityUtils.getSubject();
        final Principal principal = (Principal) currentUser.getPrincipal();

        if (!principal.isCompanyType()) {
            return orderMapper.selectByCompanyWithStatus(principal.getCompanyId(), status, null);
        } else {
            return orderMapper.selectByCompanyWithStatus(null, status, null);
        }

    }

    @Override
    public List<Order> listByStatus(final Integer status1, final Integer status2) {

        Subject currentUser = SecurityUtils.getSubject();
        final Principal principal = (Principal) currentUser.getPrincipal();

        if (!principal.isCompanyType()) {
            return orderMapper
                .selectByCompanyWithStatus(principal.getCompanyId(), status1, status2);
        } else {
            return orderMapper.selectByCompanyWithStatus(null, status1, status2);
        }

    }

    @Override
    public List<Order> listByDriverAndStatus(Long driverId, Integer status) {

        return orderMapper.selectByDriverWithStatus(driverId, status, null);

    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Order> modifyCash(Order order, BigDecimal couponMoney, BigDecimal cashMoney,
        BigDecimal signMoney,
        BigDecimal balanceMoney, BigDecimal alipayMoney, BigDecimal weixinMoney,
        BigDecimal driverMoney,
        BigDecimal memberMoney, BigDecimal wxMoney, String content) {

        if (null == couponMoney) {
            couponMoney = BigDecimal.ZERO;
        }
        if (null == cashMoney) {
            cashMoney = BigDecimal.ZERO;
        }
        if (null == signMoney) {
            signMoney = BigDecimal.ZERO;
        }
        if (null == balanceMoney) {
            balanceMoney = BigDecimal.ZERO;
        }
        if (null == alipayMoney) {
            alipayMoney = BigDecimal.ZERO;
        }
        if (null == weixinMoney) {
            weixinMoney = BigDecimal.ZERO;
        }

        final BigDecimal newCash = couponMoney.add(cashMoney).add(signMoney).add(balanceMoney)
            .add(alipayMoney)
            .add(weixinMoney);

        Result<Order> vo = new Result<Order>();

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        BigDecimal oldCash = order.getRealCash();

        order.setRealCash(newCash);
        order.setCouponMoney(couponMoney);
        order.setCashMoney(cashMoney);
        order.setSignMoney(signMoney);
        order.setBalanceMoney(balanceMoney);
        order.setAlipayMoney(alipayMoney);
        order.setWeixinMoney(weixinMoney);
        orderMapper.updateByPrimaryKey(order);

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.modifycash);
        os.setContent(
            "【" + principal.getUsername() + "】将订单金额由￥" + oldCash + "修改为￥" + newCash + "，原因："
                + content);
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        // 订单结算信息
        OrderFinishedInfo orderFinishedInfo = orderFinishedInfoMapper.selectByOrder(order.getId());
        if (null != orderFinishedInfo) {
            orderFinishedInfo.setRealCash(newCash);
            orderFinishedInfo.setCouponMoney(couponMoney);
            orderFinishedInfo.setCashMoney(cashMoney);
            orderFinishedInfo.setSignMoney(signMoney);
            orderFinishedInfo.setBalanceMoney(balanceMoney);
            orderFinishedInfo.setAlipayMoney(alipayMoney);
            orderFinishedInfo.setWeixinMoney(weixinMoney);
        }

        Driver driver = driverMapper.selectByPrimaryKey(order.getDriverId());

        if (driverMoney.compareTo(BigDecimal.ZERO) != 0) {
            driver.setVirtual(driver.getVirtual().add(driverMoney));
            driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

            DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
            driverPaymentsRecord.setMoney(driverMoney.abs());
            driverPaymentsRecord.setAfterMoney(driver.getVirtual());
            driverPaymentsRecord.setDriverId(driver.getId());
            driverPaymentsRecord.setDriverRealName(driver.getRealname());
            driverPaymentsRecord.setDriverUserName(driver.getUsername());
            driverPaymentsRecord.setDriverPhone(driver.getPhone());
            driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
            driverPaymentsRecord.setOrderId(order.getId());
            driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
            driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
            driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
            driverPaymentsRecord
                .setMemo(os.getContent() + "，订单号【<a target='_blank' href='/order/detail/"
                    + order.getId() + "'>" + order.getOrderNumber() + "</a>】");
            driverPaymentsRecord.setOperating(principal.getUsername());
            if (driverMoney.doubleValue() > 0) {
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_MODIFY);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
            } else {
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMED_TYPE_MODIFY);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
            }
            driverPaymentsRecord.setHappend(new Date());
            driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

            if (null != orderFinishedInfo) {
                orderFinishedInfo
                    .setDriverMoney(orderFinishedInfo.getDriverMoney().add(driverMoney));
            }
        }

        if (memberMoney.compareTo(BigDecimal.ZERO) != 0) {

            Result<Passenger> result_p = passengerApi
                .findOnePassenger(order.getClientId(), settingUtils.get());
            Passenger passenger = result_p.getResult();

            if (null != passenger) {

                String memo =
                    os.getContent() + "，订单号【<a target='_blank' href='/order/detail/" + order.getId()
                        + "'>"
                        + order.getOrderNumber() + "</a>】";

                if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                    passengerApi.createPassengerAccount(passenger, null, memberMoney,
                        PassengerAccount.PayType.CASH_MODIFY, principal.getUsername(), memo,
                        order.getId(),
                        order.getOrderNumber(), PassengerAccount.ORDER_TYPE_DAIJIA, null, true,
                        false,
                        settingUtils.get());
                } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                    Enterprise enterprise = passengerApi
                        .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                        .getResult();
                    if (null != enterprise) {
                        passengerApi.createEnterpriseAccount(enterprise, memberMoney,
                            PassengerAccount.PayType.CASH_MODIFY, principal.getUsername(), memo,
                            order.getId(),
                            order.getOrderNumber(), PassengerAccount.ORDER_TYPE_DAIJIA, null, true,
                            false,
                            settingUtils.get());
                    }
                }

            }
        }

        // 客户经理提成
        BigDecimal financialCash = driverMoney.multiply(new BigDecimal(-1));
        if (null != wxMoney) {
            WeixinManagerXOrder wxo = weixinManagerXOrderMapper.selectByOrderId(order.getId());

            if (null != wxo) {
                BigDecimal oldMoney = wxo.getMoney();
                wxo.setMoney(wxo.getMoney().add(wxMoney));
                if (StringUtils.isBlank(wxo.getMemo())) {
                    wxo.setMemo(
                        "【" + principal.getUsername() + "】将订单金额由￥" + oldCash + "修改为￥" + newCash
                            + "，原因："
                            + content + "，修改前￥" + oldMoney + "，修改后￥" + wxo.getMoney() + "");
                } else {
                    wxo.setMemo(
                        wxo.getMemo() + " ; " + "<br/>【" + principal.getUsername() + "】将订单金额由￥"
                            + oldCash
                            + "修改为￥" + newCash + "，原因：" + content + "，修改前￥" + oldMoney + "，修改后￥"
                            + wxo.getMoney() + "");
                }

                weixinManagerXOrderMapper.updateByPrimaryKey(wxo);

                WeixinManager weixinManager = weixinManagerMapper
                    .selectByPrimaryKey(wxo.getManagerId());
                if (null != weixinManager) {
                    weixinManager.setVirtual(weixinManager.getVirtual().add(wxMoney));
                    weixinManagerMapper.updateByPrimaryKey(weixinManager);
                    financialCash = financialCash.add(wxMoney.multiply(new BigDecimal(-1)));
                }

                if (null != orderFinishedInfo) {
                    orderFinishedInfo
                        .setWxManagerMoney(orderFinishedInfo.getWxManagerMoney().add(wxMoney));
                }

            }
        }

        FinancialRecord financialRecord = financialRecordMapper
            .selectByOrderIdAndOrderType(order.getId(),
                FinancialRecord.FINANCIALRECORD_TYPE_SHOURU, FinancialRecord.ORDER_TYPE_DAIJIA);
        if (null != financialRecord) {
            BigDecimal oldMoney = financialRecord.getMoney();

            financialRecord.setMoney(financialRecord.getMoney().add(financialCash));
            financialRecord.setMemo(
                financialRecord.getMemo() + " ; " + "<br/>【" + principal.getUsername() + "】将订单金额由￥"
                    + oldCash + "修改为￥" + newCash + "，原因：" + content + "，修改前￥" + oldMoney + "，修改后￥"
                    + financialRecord.getMoney() + "");
            financialRecordMapper.updateByPrimaryKey(financialRecord);

            if (null != orderFinishedInfo) {
                orderFinishedInfo
                    .setCompanyMoney(orderFinishedInfo.getCompanyMoney().add(financialCash));
            }
        }

        if (null != orderFinishedInfo) {
            orderFinishedInfoMapper.updateByPrimaryKey(orderFinishedInfo);
        }

        // 更新订单记录
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(order.getFinishTime());
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);

        ChartYear chartYear = chartYearService.findByYearAndCompany(year, order.getCompanyId());
        if (null != chartYear) {

            chartYear.setTotalPrice(chartYear.getTotalPrice().add(newCash.subtract(oldCash)));
            chartYearService.updateByPrimaryKey(chartYear);

            ChartMonth chartMonth = chartMonthMapper.selectByYearAndMonth(chartYear.getId(), month);
            if (null != chartMonth) {

                chartMonth.setTotalPrice(chartMonth.getTotalPrice().add(newCash.subtract(oldCash)));
                chartMonthMapper.updateByPrimaryKey(chartMonth);

                ChartDay chartDay = chartDayMapper.selectByMonthAndDay(chartMonth.getId(), day);
                if (null != chartDay) {

                    Class<ChartDay> clazz = ChartDay.class;

                    Method getMethod = ReflectionUtils
                        .findMethod(clazz, "getHour" + hour + "TotalPrice");
                    Method setMethod = ReflectionUtils
                        .findMethod(clazz, "setHour" + hour + "TotalPrice",
                            BigDecimal.class);

                    BigDecimal money = (BigDecimal) ReflectionUtils
                        .invokeMethod(getMethod, chartDay);
                    ReflectionUtils
                        .invokeMethod(setMethod, chartDay, money.add(newCash.subtract(oldCash)));

                    chartDay.setTotalPrice(chartDay.getTotalPrice().add(newCash.subtract(oldCash)));
                    chartDayMapper.updateByPrimaryKey(chartDay);
                }
            }
        }

        final String clientPhone = order.getClientPhone();
        final String orderNumber = order.getOrderNumber();
        final Long companyId = order.getCompanyId();
        Company orderCompany = companyMapper.selectByPrimaryKey(companyId);

        Company main = companyMapper.selectMainCompany();
        Setting setting = settingUtils.get();
        if (!main.getId().equals(orderCompany.getId()) && setting.isSmsMainCompany()) {
            orderCompany = main;
        }
        final Company finalCompany = orderCompany;

        taskExecutor.execute(new Runnable() {
            public void run() {
                // 短信
                int ret = -99;
                try {
                    Company mainCompany = companyMapper.selectMainCompany();
                    SmsTemplet templet = smsService
                        .findByAlias(finalCompany.getId(), SmsType.modifyCash);

                    if (null != templet && StringUtils.isNotBlank(templet.getContent())) {
                        ret = smsService.sendSms(clientPhone, "modifyCash",
                            "{\"订单号\":\"" + "***" + orderNumber.substring(8) + "\",\"收费金额\":\""
                                + newCash + ""
                                + "\",\"投诉建议电话\":\"" + finalCompany.getTelephone() + "\"}",
                            finalCompany.getId(), 0, finalCompany.getSignName());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                logger.debug("修改订单金额短信结果：" + ret);

            }
        });

        vo.setSuccess(true);
        return vo;

    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Order> updateInfo(Order order, String fromPlace, String clientPhone,
        String userPhone,
        String clientName) {

        Result<Order> vo = new Result<Order>();

        if (StringUtils.isNotBlank(fromPlace)) {
            order.setFromPlace(fromPlace);
        }
        if (StringUtils.isNotBlank(clientPhone)) {
            order.setClientPhone(clientPhone);
        }
        if (StringUtils.isNotBlank(userPhone)) {
            order.setUserPhone(userPhone);
        }
        if (StringUtils.isNotBlank(clientName)) {
            order.setClientName(clientName);
        }

        if (StringUtils.isNotBlank(clientPhone)) {
            Passenger passenger = passengerApi
                .findOnePassengerByPhone(clientPhone, settingUtils.get()).getResult();
            if (null != passenger) {
                if (StringUtils.isNotBlank(clientName)) {
                    passenger.setName(clientName);
                    passengerApi.updatePersonal(passenger, settingUtils.get());
                }
            } else {
                // 新客户
                passenger = new Passenger();
                passenger.setName(clientName);
                passenger.setPhone(order.getClientPhone());
                passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_PHONE);
                passenger.setType(Passenger.TYPE_PASSENGER);
                passenger.setAllowOverdraw(false);
                passenger.setLongitude(order.getClientLongitude());
                passenger.setLatitude(order.getClientLatitude());
                Company company = companyMapper.selectByPrimaryKey(order.getCompanyId());
                passenger.setCompanyId(company.getId());
                passenger.setCompanyName(company.getAbbreviation());

                passenger = passengerApi.createPersonal(passenger, settingUtils.get()).getResult();

                order.setClientId(passenger.getId());
            }
        }

        orderMapper.updateByPrimaryKey(order);

        vo.setSuccess(true);
        return vo;
    }

    @Override
    // public Result<Order> getTuijianMoney(Order order, BigDecimal cash) {
    //
    // Result<Order> vo = new Result<Order>();
    //
    // Map<String, Object> map = new HashMap<String, Object>();
    //
    // BigDecimal oldCash = order.getRealCash();
    //
    // Driver driver = driverMapper.selectByPrimaryKey(order.getDriverId());
    //
    // BigDecimal driverMoney = BigDecimal.ZERO;
    // BigDecimal memberMoney = BigDecimal.ZERO;
    //
    // BigDecimal chaMoney = BigDecimal.ZERO;
    //
    // //客户经理
    // BigDecimal money1 = BigDecimal.ZERO;
    // BigDecimal money2 = BigDecimal.ZERO;
    // WeixinManagerXOrder wxo =
    // weixinManagerXOrderMapper.selectByOrderId(order.getId());
    // if (null != wxo) {
    // WeixinManager weixinManager =
    // weixinManagerMapper.selectByPrimaryKey(wxo.getManagerId());
    // if (null != weixinManager) {
    // if
    // (weixinManager.getWeixinManagerMoneyType().equals(WeixinManagerMoneyType.guding))
    // {
    // money1 = weixinManager.getFixedMoney();
    // money2 = weixinManager.getFixedMoney();
    // } else if
    // (weixinManager.getWeixinManagerMoneyType().equals(WeixinManagerMoneyType.bili))
    // {
    // money1 = oldCash.multiply(weixinManager.getRatioMoney()).divide(new
    // BigDecimal(100));
    // money2 = cash.multiply(weixinManager.getRatioMoney()).divide(new
    // BigDecimal(100));
    // }
    // map.put("wxMoney", money2.subtract(money1));
    // }
    // }
    //
    //
    // if (null != driver && null != driver.getType() &&
    // Driver.DRIVER_TYPR_PARTTIME.equals(driver.getType())) {
    //
    // DriverChoseLevel driverChoseLevel = null;
    // DriverChoseLevelCar driverChoseLevelCar = null;
    // driverChoseLevel =
    // driverChoseLevelMapper.selectByDriverAndCompany(driver.getId(),
    // order.getCompanyId());
    //
    // if (null != driverChoseLevel || null != driverChoseLevelCar) {
    //
    // DriverLevel driverLevel = null;
    // if (null != driverChoseLevel) {
    // if (driverChoseLevel.getDriverlevelId() == 0) {//始终使用本公司提成
    // DriverChoseLevel driverChoseLevel2 =
    // driverChoseLevelMapper.selectByDriverAndCompany(driver.getId(),
    // driver.getCompanyId());
    // if (null != driverChoseLevel2) {
    // driverLevel =
    // driverLevelMapper.selectByPrimaryKey(driverChoseLevel2.getDriverlevelId());
    // }
    // } else {
    // driverLevel =
    // driverLevelMapper.selectByPrimaryKey(driverChoseLevel.getDriverlevelId());
    // }
    // } else if (null != driverChoseLevelCar) {
    // if (driverChoseLevelCar.getDriverlevelId() == 0) {//始终使用本公司提成
    // DriverChoseLevelCar driverChoseLevelCar2 =
    // driverChoseLevelCarMapper.selectByDriverAndCompany(driver.getId(),
    // driver.getCompanyId());
    // if (null != driverChoseLevelCar2) {
    // driverLevel =
    // driverLevelMapper.selectByPrimaryKey(driverChoseLevelCar2.getDriverlevelId());
    // }
    // } else {
    // driverLevel =
    // driverLevelMapper.selectByPrimaryKey(driverChoseLevelCar.getDriverlevelId());
    // }
    // }
    //
    // DriverLevelDetail detail = null;
    //
    // if (null != driverLevel) {
    // driverLevel.setDriverLevelDetails(driverLevelDetailMapper.selectByDriverLevel(driverLevel.getId()));
    // driverLevel.setDriverLevelMoneyTimeDetails(driverLevelMoneyTimeDetailMapper.selectByDriverLevel(driverLevel.getId()));
    // detail = driverLevel.getDeatil(order.getDaijiaTime());
    // }
    //
    // if (null != detail) {
    // if (order.getPayType().compareTo(PayType.cash) == 0) {//现金
    //
    // DriverConsumedRecord dcr =
    // driverConsumedRecordMapper.selectTichengByOrderId(order.getId());
    // if (null != dcr) {
    // if ((detail.getDriverLevelType().equals(DriverLevelType.ticheng) &&
    // cash.compareTo(detail.getMinCommission()) != -1) ||
    // (detail.getDriverLevelType().equals(DriverLevelType.guding) &&
    // cash.compareTo(detail.getMinMoney()) != -1)) {
    //
    // chaMoney = (oldCash.subtract(money1)).subtract(cash.subtract(money2));
    //
    // if (detail.getDriverLevelType().equals(DriverLevelType.ticheng)) {
    // driverMoney = chaMoney.multiply(detail.getCommission()).divide(new
    // BigDecimal(100));
    // } else if (detail.getDriverLevelType().equals(DriverLevelType.guding)) {
    // driverMoney = BigDecimal.ZERO;
    // }
    //
    // }
    // }
    // } else {
    // chaMoney = (cash.subtract(money2)).subtract(oldCash.subtract(money1));
    //
    // if (detail.getDriverLevelType().equals(DriverLevelType.ticheng)) {
    // if (cash.compareTo(detail.getMinCommission()) == -1) {
    // driverMoney = chaMoney;
    // } else {
    // driverMoney = chaMoney.multiply(new
    // BigDecimal(100).subtract(detail.getCommission())).divide(new
    // BigDecimal(100));
    // }
    // } else if (detail.getDriverLevelType().equals(DriverLevelType.guding)) {
    // if (cash.compareTo(detail.getMinMoney()) == -1) {
    // driverMoney = chaMoney;
    // } else {
    // driverMoney = chaMoney;
    // }
    // }
    //
    // }
    //
    // }
    //
    // }
    //
    // }
    //
    // memberMoney = oldCash.subtract(cash);
    //
    // map.put("driverMoney", driverMoney);
    // map.put("memberMoney", memberMoney);
    //
    // vo.setMap(map);
    // vo.setSuccess(true);
    //
    // return vo;
    //
    // }
    @Transactional(rollbackFor = Exception.class)
    public Result<Order> weixinOrder(Order order, Driver driver, Passenger passenger) {

        Result<Order> vo = new Result<Order>();

        Double longitude = order.getClientLongitude();
        Double latitude = order.getClientLatitude();
        String fromPlace = order.getFromPlace();

        passengerApi.updatePassengerFromPlace(passenger.getId(), fromPlace, longitude, latitude,
            settingUtils.get());
        // memberMapper.updatePosByPrimaryKey(longitude, latitude,
        // passenger.getId());

        DateFormat format = new SimpleDateFormat("yyyyMMdd");

        order.setClientId(passenger.getId());

        order.setStatus(Order.ORDER_STATUS_YIPAIDAN);
        order.setOrderType(Order.ORDER_TYPE_WEIXIN);

        if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
            order.setMemberType(Order.ORDER_MEMBER_TYPE_PASSENGER);
        } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
            order.setMemberType(Order.ORDER_MEMBER_TYPE_ENTERPRISE);
        }

        order.setCompanyId(driver.getCompanyId());
        order.setDriverId(driver.getId());
        order.setDriverName(driver.getName());
        order.setDriverRealName(driver.getRealname());
        order.setDriverPhone(driver.getPhone());

        if (passenger.isInBlackList()) {
            order.setMemo("黑名单客户");
        }

        // 生成订单号
        StringBuilder sb = new StringBuilder();

        sb.append(OrderNumberConfig.WEIXIN);// 微信
        if (null != passenger && passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
            sb.append(OrderNumberConfig.COMPANY);// 企业用户
        } else {
            sb.append(OrderNumberConfig.CUSTOMER);// 普通用户
        }
        sb.append(format.format(new Date()));// 年月日时间
        sb.append(OrderNumberConfig.padZero(orderMapper.getRunningNumber() + 1));// 流水号
        order.setOrderNumber(sb.toString());

        orderMapper.insertRecord(order);

        // 设置服务人员为接单
        driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_APPLY_ORDER,
            Driver.DRIVER_JOBSTATUS_DAIJIA,
            driver.getId());
        driver.setStatus(Driver.DRIVER_APPLY_ORDER);

        // 扣费
        Setting setting = settingUtils.get();

        if (setting.getInfoFee() != 0) {
            if (null != setting.getInfoFeeType() && setting.getInfoFeeType()
                .equals(InfoFeeType.paidan)) {
                driver
                    .setVirtual(driver.getVirtual().subtract(new BigDecimal(setting.getInfoFee())));
                driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                // 扣费记录
                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                driverPaymentsRecord.setMoney(new BigDecimal(setting.getInfoFee()));
                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                driverPaymentsRecord.setDriverId(driver.getId());
                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                driverPaymentsRecord.setOrderId(order.getId());
                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                driverPaymentsRecord.setMemo("扣除公司所得保险费/信息费" + setting.getInfoFee() + "元。");
                driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                driverPaymentsRecord.setHappend(new Date());
                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                // 财务记录（保险费/信息费）
                Company mainCompany = companyMapper.selectMainCompany();
                DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb_f = new StringBuilder();
                sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 报销金额
                sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                sb_f.append(format_f.format(new Date()));// 年月日时间
                sb_f.append(
                    OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                financialRecord.setCode(sb_f.toString());
                financialRecord.setCompanyId(mainCompany.getId());
                financialRecord.setCompanyName(mainCompany.getAbbreviation());
                financialRecord.setOrderCompanyId(mainCompany.getId());
                financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                financialRecord
                    .setMemo("订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                        + order.getOrderNumber() + "</a>】保险费/信息费");
                financialRecord.setMoney(new BigDecimal(setting.getInfoFee()));
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                financialRecord.setWho(driver.getRealname());
                financialRecord.setOrderId(order.getId());
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                financialRecordMapper.insertRecord(financialRecord);
            }
        }

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.paidan);
        os.setContent("【" + passenger.getName() + "】从微信下单给服务人员【" + driver.getRealname() + "】");
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        // 派单事件
        order.setRinging(true);
        OrderPaidanEvent paidanEvent = new OrderPaidanEvent(order);
        applicationEventMulticaster.multicastEvent(paidanEvent);

        OrderRecordEvent orderRecordEvent = new OrderRecordEvent(order);
        applicationEventMulticaster.multicastEvent(orderRecordEvent);

        vo.setSuccess(true);
        return vo;

    }

    @Transactional(rollbackFor = Exception.class)
    public List<Order> managerBook(WeixinManager weixinManager, Order order, Integer driverNum) {

        Company company = null;
        if (null != weixinManager.getCompanyId()) {
            company = companyMapper.selectByPrimaryKey(weixinManager.getCompanyId());
        } else {
            company = companyMapper.selectMainCompany();
        }

        Double longitude = order.getClientLongitude();
        Double latitude = order.getClientLatitude();

        // weixinManager.setLongitude(longitude);
        // weixinManager.setLatitude(latitude);
        // weixinManager.setPlace(order.getFromPlace());
        // weixinManagerMapper.updateByPrimaryKey(weixinManager);

        // 根据客户电话查询客户
        Result<Passenger> result_p = passengerApi
            .findOnePassengerByPhone(order.getClientPhone(), settingUtils.get());
        Passenger passenger = result_p.getResult();
        if (null != passenger) {
            // 老客户 更新位置
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            if (!StringUtils.isBlank(order.getClientName()) && StringUtils
                .isBlank(passenger.getName())) {
                passenger.setName(order.getClientName());
                passengerApi.updatePersonal(passenger, settingUtils.get());
            }
        } else {
            // 新客户
            passenger = new Passenger();
            passenger.setName(order.getClientName());
            passenger.setPhone(order.getClientPhone());
            passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_MANAGER);
            passenger.setType(Passenger.TYPE_PASSENGER);
            passenger.setAllowOverdraw(false);
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            passenger.setCompanyId(company.getId());
            passenger.setCompanyName(company.getAbbreviation());

            Result<Passenger> result = passengerApi.createPersonal(passenger, settingUtils.get());
            if (result.isSuccess()) {
                passenger = result.getResult();
            }
        }

        DateFormat format = new SimpleDateFormat("yyyyMMdd");

        order.setClientLongitude(longitude);
        order.setClientLatitude(latitude);
        order.setClientId(passenger.getId());
        order.setFromSource(Order.ORDER_TYPE_MANAGER);
        order.setOrderType(Order.ORDER_TYPE_MANAGER);

        if (passenger.isInBlackList()) {
            order.setMemo("黑名单客户");
        }

        if (driverNum > 1) {
            OrderGroup orderGroup = new OrderGroup();
            orderGroupMapper.insertRecord(orderGroup);
            order.setOrderGroupId(orderGroup.getId());
            if (StringUtils.isBlank(order.getMemo())) {
                order.setMemo("客户同时预约" + driverNum + "人");
            } else {
                order.setMemo(order.getMemo() + ";" + "客户同时预约" + driverNum + "人");
            }
        }

        List<Order> newOrders = new ArrayList<Order>();
        for (int i = 1; i <= driverNum; i++) {
            Order dborder = new Order();
            BeanUtils.copyProperties(order, dborder);
            dborder.setStatus(Order.ORDER_STATUS_NEW);

            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                dborder.setMemberType(Order.ORDER_MEMBER_TYPE_PASSENGER);
            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                dborder.setMemberType(Order.ORDER_MEMBER_TYPE_ENTERPRISE);
            }

            dborder.setCompanyId(company.getId());

            // 生成订单号
            StringBuilder sb = new StringBuilder();

            sb.append(OrderNumberConfig.MANAGER);// 客户经理
            if (null != passenger && passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                sb.append(OrderNumberConfig.COMPANY);// 企业用户
            } else {
                sb.append(OrderNumberConfig.CUSTOMER);// 普通用户
            }
            sb.append(format.format(new Date()));// 年月日时间
            sb.append(OrderNumberConfig.padZero(orderMapper.getRunningNumber() + 1));// 流水号
            dborder.setOrderNumber(sb.toString());

            orderMapper.insertRecord(dborder);
            newOrders.add(dborder);

            // 添加一条订单状态
            OrderStatus os = new OrderStatus();
            os.setOrderId(dborder.getId());
            os.setStatusType(StatusType.neworder);
            os.setContent("客户经理【" + weixinManager.getName() + "】下单");
            os.setHappened(new Date());
            orderStatusMapper.insertRecord(os);

            WeixinManagerXOrder wxo = new WeixinManagerXOrder();
            wxo.setManagerId(weixinManager.getId());
            wxo.setOrderId(dborder.getId());
            wxo.setOrderNumber(dborder.getOrderNumber());
            wxo.setMemo("");
            weixinManagerXOrderMapper.insertRecord(wxo);

        }

        for (Order order2 : newOrders) {
            OrderCreateEvent event = new OrderCreateEvent(order2);
            applicationEventMulticaster.multicastEvent(event);

            OrderRecordEvent orderRecordEvent = new OrderRecordEvent(order2);
            applicationEventMulticaster.multicastEvent(orderRecordEvent);
        }

        return newOrders;

    }

    @Transactional(rollbackFor = Exception.class)
    public List<Order> managerBookV2(WeixinManager weixinManager, Order order,
        List<String> phones) {

        Company company = companyMapper.selectByPrimaryKey(weixinManager.getCompanyId());

        Double longitude = order.getClientLongitude();
        Double latitude = order.getClientLatitude();

        List<Passenger> passengers = new ArrayList<Passenger>();
        // 根据客户电话查询客户
        for (String phone : phones) {
            Result<Passenger> result_p = passengerApi
                .findOnePassengerByPhone(phone, settingUtils.get());
            Passenger passenger = result_p.getResult();
            if (null != passenger) {
                // 老客户 更新位置
                passenger.setLongitude(longitude);
                passenger.setLatitude(latitude);
                passengerApi.updatePersonal(passenger, settingUtils.get());
            } else {
                // 新客户
                passenger = new Passenger();
                passenger.setName("先生/女士");
                passenger.setPhone(phone);
                passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_MANAGER);
                passenger.setType(Passenger.TYPE_PASSENGER);
                passenger.setAllowOverdraw(false);
                passenger.setLongitude(longitude);
                passenger.setLatitude(latitude);
                passenger.setCompanyId(company.getId());
                passenger.setCompanyName(company.getAbbreviation());

                Result<Passenger> result = passengerApi
                    .createPersonal(passenger, settingUtils.get());
                if (result.isSuccess()) {
                    passenger = result.getResult();
                }
            }
            passengers.add(passenger);
        }

        DateFormat format = new SimpleDateFormat("yyyyMMdd");

        order.setClientLongitude(longitude);
        order.setClientLatitude(latitude);
        order.setFromSource(Order.ORDER_TYPE_MANAGER);
        order.setOrderType(Order.ORDER_TYPE_MANAGER);
        order.setManagerId(weixinManager.getId());

        if (passengers.size() > 1) {
            OrderGroup orderGroup = new OrderGroup();
            orderGroupMapper.insertRecord(orderGroup);
            order.setOrderGroupId(orderGroup.getId());
            order.setMemo("客户经理客户同时预约" + passengers.size() + "人");
        }

        List<Order> newOrders = new ArrayList<Order>();
        for (Passenger p : passengers) {

            Order dborder = new Order();
            BeanUtils.copyProperties(order, dborder);
            dborder.setStatus(Order.ORDER_STATUS_NEW);

            dborder.setMemberType(Order.ORDER_MEMBER_TYPE_PASSENGER);

            dborder.setCompanyId(company.getId());

            dborder.setClientId(p.getId());
            dborder.setClientPhone(p.getPhone());
            dborder.setClientName(p.getName());
            if (p.isInBlackList()) {
                if (StringUtils.isBlank(dborder.getMemo())) {
                    dborder.setMemo("黑名单客户");
                } else {
                    dborder.setMemo(dborder.getMemo() + ";" + "黑名单客户");
                }
            }

            // 生成订单号
            StringBuilder sb = new StringBuilder();

            sb.append(OrderNumberConfig.MANAGER);// 客户经理
            sb.append(OrderNumberConfig.CUSTOMER);// 普通用户
            sb.append(format.format(new Date()));// 年月日时间
            sb.append(OrderNumberConfig.padZero(orderMapper.getRunningNumber() + 1));// 流水号
            dborder.setOrderNumber(sb.toString());

            orderMapper.insertRecord(dborder);
            newOrders.add(dborder);

            // 添加一条订单状态
            OrderStatus os = new OrderStatus();
            os.setOrderId(dborder.getId());
            os.setStatusType(StatusType.neworder);
            os.setContent("客户经理【" + weixinManager.getName() + "】下单");
            os.setHappened(new Date());
            orderStatusMapper.insertRecord(os);

            WeixinManagerXOrder wxo = new WeixinManagerXOrder();
            wxo.setManagerId(weixinManager.getId());
            wxo.setOrderId(dborder.getId());
            wxo.setOrderNumber(dborder.getOrderNumber());
            wxo.setMemo("");
            weixinManagerXOrderMapper.insertRecord(wxo);

        }

        for (Order order2 : newOrders) {
            OrderCreateEvent event = new OrderCreateEvent(order2);
            applicationEventMulticaster.multicastEvent(event);

            OrderRecordEvent orderRecordEvent = new OrderRecordEvent(order2);
            applicationEventMulticaster.multicastEvent(orderRecordEvent);
        }

        return newOrders;

    }

    @Transactional(rollbackFor = Exception.class)
    public Order memberBook(Order order, String wxuser) {

        Company company = companyMapper.selectMainCompany();

        Double longitude = order.getClientLongitude();
        Double latitude = order.getClientLatitude();

        // 根据客户电话查询客户
        Result<Passenger> result_p = passengerApi
            .findOnePassengerByPhone(order.getClientPhone(), settingUtils.get());
        Passenger passenger = result_p.getResult();
        if (null != passenger) {
            // 老客户 更新位置
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            passengerApi.updatePersonal(passenger, settingUtils.get());
        } else {
            // 新客户
            passenger = new Passenger();
            passenger.setPhone(order.getClientPhone());
            if (StringUtils.isNotBlank(wxuser)) {
                passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_WEIXIN);
            } else {
                passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_WEB);
            }
            passenger.setType(Passenger.TYPE_PASSENGER);
            passenger.setAllowOverdraw(false);
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            passenger.setCompanyId(company.getId());
            passenger.setCompanyName(company.getAbbreviation());

            Result<Passenger> result = passengerApi.createPersonal(passenger, settingUtils.get());
            if (result.isSuccess()) {
                passenger = result.getResult();
            }
        }

        DateFormat format = new SimpleDateFormat("yyyyMMdd");

        order.setClientId(passenger.getId());
        if (StringUtils.isNotBlank(wxuser)) {
            order.setFromSource(Order.ORDER_TYPE_WEIXIN);
            order.setOrderType(Order.ORDER_TYPE_WEIXIN);
        } else {
            order.setFromSource(Order.ORDER_TYPE_WEB);
            order.setOrderType(Order.ORDER_TYPE_WEB);
        }

        if (passenger.isInBlackList()) {
            order.setMemo("黑名单客户");
        }

        order.setStatus(Order.ORDER_STATUS_NEW);

        if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
            order.setMemberType(Order.ORDER_MEMBER_TYPE_PASSENGER);
        } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
            order.setMemberType(Order.ORDER_MEMBER_TYPE_ENTERPRISE);
        }

        // 生成订单号
        StringBuilder sb = new StringBuilder();

        if (StringUtils.isNotBlank(wxuser)) {
            sb.append(OrderNumberConfig.WEIXIN);// 微信
        } else {
            sb.append(OrderNumberConfig.WEB);// 网站
        }

        if (null != passenger && passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
            sb.append(OrderNumberConfig.COMPANY);// 企业用户
        } else {
            sb.append(OrderNumberConfig.CUSTOMER);// 普通用户
        }
        sb.append(format.format(new Date()));// 年月日时间
        sb.append(OrderNumberConfig.padZero(orderMapper.getRunningNumber() + 1));// 流水号
        order.setOrderNumber(sb.toString());

        orderMapper.insertRecord(order);

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.neworder);
        os.setContent("客户【" + order.getClientName() + "】下单");
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        phoneSmsRecordMapper.deleteByPhone(order.getClientPhone());

        OrderCreateEvent event = new OrderCreateEvent(order);
        applicationEventMulticaster.multicastEvent(event);

        OrderRecordEvent orderRecordEvent = new OrderRecordEvent(order);
        applicationEventMulticaster.multicastEvent(orderRecordEvent);

        return order;

    }

    @Override
    public List<Order> rushOrder(Double longitude, Double latitude, Driver driver) {
        Setting setting = settingUtils.get();

        List<Order> list = orderMapper.selectRushOrders();

        List<Order> newlist = new ArrayList<Order>();
        if (!CollectionUtils.isEmpty(list)) {
            long nowtime = System.currentTimeMillis();
            for (Order order : list) {
                if (nowtime >= (order.getCreated().getTime() + (setting.getRushOrderTime3()
                    * 1000))) {
                    double distance = Distance
                        .doubleVal(order.getClientLatitude(), order.getClientLongitude(),
                            latitude, longitude);
                    if (distance <= setting.getRushOrderKm3()) {
                        newlist.add(order);
                    }
                } else if (nowtime >= (order.getCreated().getTime() + (setting.getRushOrderTime2()
                    * 1000))) {
                    double distance = Distance
                        .doubleVal(order.getClientLatitude(), order.getClientLongitude(),
                            latitude, longitude);
                    if (distance <= setting.getRushOrderKm2()) {
                        newlist.add(order);
                    }
                } else if (nowtime >= (order.getCreated().getTime() + (setting.getRushOrderTime1()
                    * 1000))) {
                    double distance = Distance
                        .doubleVal(order.getClientLatitude(), order.getClientLongitude(),
                            latitude, longitude);
                    if (distance <= setting.getRushOrderKm1()) {
                        newlist.add(order);
                    }
                }
            }
        }

        return newlist;
    }

    @Transactional(rollbackFor = Exception.class)
    public Order webOrder(Order order) {

        Company company = companyMapper.selectMainCompany();

        Double longitude = order.getClientLongitude();
        Double latitude = order.getClientLatitude();

        // 根据客户电话查询客户
        Result<Passenger> result_p = passengerApi
            .findOnePassengerByPhone(order.getClientPhone(), settingUtils.get());
        Passenger passenger = result_p.getResult();
        if (null != passenger) {
            // 老客户 更新位置
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            if (!StringUtils.isBlank(order.getClientName()) && StringUtils
                .isBlank(passenger.getName())) {
                passenger.setName(order.getClientName());
                passengerApi.updatePersonal(passenger, settingUtils.get());
            }
        } else {
            // 新客户
            passenger = new Passenger();
            passenger.setName(order.getClientName());
            passenger.setPhone(order.getClientPhone());
            passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_WEB);
            passenger.setType(Passenger.TYPE_PASSENGER);
            passenger.setAllowOverdraw(false);
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            passenger.setCompanyId(company.getId());
            passenger.setCompanyName(company.getAbbreviation());

            Result<Passenger> result = passengerApi.createPersonal(passenger, settingUtils.get());
            if (result.isSuccess()) {
                passenger = result.getResult();
            }

        }

        DateFormat format = new SimpleDateFormat("yyyyMMdd");

        order.setClientId(passenger.getId());

        order.setStatus(Order.ORDER_STATUS_NEW);
        order.setOrderType(Order.ORDER_TYPE_WEB);

        if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
            order.setMemberType(Order.ORDER_MEMBER_TYPE_PASSENGER);
        } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
            order.setMemberType(Order.ORDER_MEMBER_TYPE_ENTERPRISE);
        }

        order.setCompanyId(company.getId());

        if (passenger.isInBlackList()) {
            order.setMemo("黑名单客户");
        }

        // 生成订单号
        StringBuilder sb = new StringBuilder();

        sb.append(OrderNumberConfig.WEB);// 网站
        if (null != passenger && passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
            sb.append(OrderNumberConfig.COMPANY);// 企业用户
        } else {
            sb.append(OrderNumberConfig.CUSTOMER);// 普通用户
        }
        sb.append(format.format(new Date()));// 年月日时间
        sb.append(OrderNumberConfig.padZero(orderMapper.getRunningNumber() + 1));// 流水号
        order.setOrderNumber(sb.toString());

        orderMapper.insertRecord(order);

        List<Order> newOrders = new ArrayList<Order>();
        newOrders.add(order);

        OrderCreateEvent event = new OrderCreateEvent(order);
        applicationEventMulticaster.multicastEvent(event);

        OrderRecordEvent orderRecordEvent = new OrderRecordEvent(order);
        applicationEventMulticaster.multicastEvent(orderRecordEvent);

        return order;

    }

    @Override
    public List<Order> listWorkingOrdersByDriver(Long driverId) {

        return orderMapper.selectByDriverWithStatus(driverId, Order.ORDER_STATUS_YIPAIDAN,
            Order.ORDER_STATUS_BUSY);

    }

    @Transactional(rollbackFor = Exception.class)
    public void zhuandan(Order order, Driver driver, Driver oldDriver) {

        String oldDriverName = oldDriver.getRealname();

        order.setDriverId(driver.getId());
        order.setDriverName(driver.getName());
        order.setDriverRealName(driver.getRealname());
        order.setDriverPhone(driver.getPhone());
        order.setStatus(Order.ORDER_STATUS_YIPAIDAN);
        orderMapper.updateByPrimaryKey(order);

        // 设置服务人员为接单
        driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_APPLY_ORDER,
            Driver.DRIVER_JOBSTATUS_DAIJIA,
            driver.getId());
        driver.setStatus(Driver.DRIVER_APPLY_ORDER);

        List<Order> oldBusyOrders = orderMapper
            .selectByDriverWithStatus(oldDriver.getId(), Order.ORDER_STATUS_BUSY,
                null);
        if (CollectionUtils.isEmpty(oldBusyOrders)) {
            List<Order> oldPaidanOrders = orderMapper.selectByDriverWithStatus(oldDriver.getId(),
                Order.ORDER_STATUS_YIPAIDAN, null);
            if (CollectionUtils.isEmpty(oldPaidanOrders)) {
                driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null,
                    oldDriver.getId());
                oldDriver.setStatus(Driver.DRIVER_ONLINE);
            }
        }

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.paidan);
        os.setContent("【" + oldDriverName + "】转单给服务人员：" + driver.getRealname());
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        // 转单事件
        ReactorVo rVo = new ReactorVo();
        rVo.setOrder(order);
        rVo.setDriver(oldDriver);
        OrderZhuandanEvent zhuandanEvent = new OrderZhuandanEvent(rVo);
        applicationEventMulticaster.multicastEvent(zhuandanEvent);

    }

    @Transactional(rollbackFor = Exception.class)
    public void powerZhuandan(Order order, Driver driver, Driver oldDriver) {

        String oldDriverName = oldDriver.getRealname();

        order.setDriverId(driver.getId());
        order.setDriverName(driver.getName());
        order.setDriverRealName(driver.getRealname());
        order.setDriverPhone(driver.getPhone());
        order.setStatus(Order.ORDER_STATUS_YIPAIDAN);
        orderMapper.updateByPrimaryKey(order);

        // 设置服务人员为接单
        driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_APPLY_ORDER,
            Driver.DRIVER_JOBSTATUS_DAIJIA,
            driver.getId());
        driver.setStatus(Driver.DRIVER_APPLY_ORDER);

        List<Order> oldBusyOrders = orderMapper
            .selectByDriverWithStatus(oldDriver.getId(), Order.ORDER_STATUS_BUSY,
                null);
        if (CollectionUtils.isEmpty(oldBusyOrders)) {
            List<Order> oldPaidanOrders = orderMapper.selectByDriverWithStatus(oldDriver.getId(),
                Order.ORDER_STATUS_YIPAIDAN, null);
            if (CollectionUtils.isEmpty(oldPaidanOrders)) {
                driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null,
                    oldDriver.getId());
                oldDriver.setStatus(Driver.DRIVER_ONLINE);
            }
        }

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.paidan);
        os.setContent("【" + oldDriverName + "】转单给服务人员：" + driver.getRealname());
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        // 强制转单事件
        ReactorVo rVo = new ReactorVo();
        rVo.setOrder(order);
        rVo.setDriver(oldDriver);
        OrderZhuandanEvent zhuandanEvent = new OrderZhuandanEvent(rVo);
        applicationEventMulticaster.multicastEvent(zhuandanEvent);

    }

    @Transactional(rollbackFor = Exception.class)
    public void zhuandanV4(Order order, Driver driver, Driver oldDriver) {

        String oldDriverName = oldDriver.getRealname();

        order.setDriverId(driver.getId());
        order.setDriverName(driver.getName());
        order.setDriverRealName(driver.getRealname());
        order.setDriverPhone(driver.getPhone());
        order.setArrivePlaceDate(null);
        order.setStartDriveDate(null);
        order.setStatus(Order.ORDER_STATUS_YIPAIDAN);
        orderMapper.updateByPrimaryKey(order);

        // 设置服务人员为接单
        driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_APPLY_ORDER,
            Driver.DRIVER_JOBSTATUS_DAIJIA,
            driver.getId());
        driver.setStatus(Driver.DRIVER_APPLY_ORDER);

        driverMapper
            .updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null, oldDriver.getId());
        oldDriver.setStatus(Driver.DRIVER_ONLINE);

        // 添加一条订单状态
        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.paidan);
        os.setContent("【" + oldDriverName + "】转单给服务人员：" + driver.getRealname());
        os.setHappened(new Date());
        orderStatusMapper.insertRecord(os);

        // 转单事件
        ReactorVo rVo = new ReactorVo();
        rVo.setOrder(order);
        rVo.setDriver(oldDriver);
        OrderZhuandanEvent zhuandanEvent = new OrderZhuandanEvent(rVo);
        applicationEventMulticaster.multicastEvent(zhuandanEvent);

    }

    @Override
    public Page<Order> pageByMembmerAndStatus(Long clientId, Integer status, Integer page,
        Integer limit) {

        Pageable pageable = new PageRequest(page, limit);

        List<Order> content = orderMapper
            .selectByMemberWithStatus(clientId, status, null, null, page * limit, limit);
        long total = orderMapper.countByMemberWithStatus(clientId, status, null, null);

        return new PageImpl<Order>(content, pageable, total);

    }

    @Override
    public Page<Order> pageByMembmerAndStatus(Long clientId, Integer status1, Integer status2,
        Integer page,
        Integer limit) {

        Pageable pageable = new PageRequest(page, limit);

        List<Order> content = orderMapper
            .selectByMemberWithStatus(clientId, status1, status2, null, page * limit,
                limit);
        long total = orderMapper.countByMemberWithStatus(clientId, status1, status2, null);

        return new PageImpl<Order>(content, pageable, total);

    }

    @Override
    public Page<Order> pageByMembmerAndStatus(Long clientId, Integer status1, Integer status2,
        Integer status3,
        Integer page, Integer limit) {

        Pageable pageable = new PageRequest(page, limit);

        List<Order> content = orderMapper
            .selectByMemberWithStatus(clientId, status1, status2, status3, page * limit,
                limit);
        long total = orderMapper.countByMemberWithStatus(clientId, status1, status2, status3);

        return new PageImpl<Order>(content, pageable, total);

    }

    @Override
    public long countByMember(String phone, Date start, Date end) {

        return orderMapper.countByMemberPhoneWithDate(phone, start, end);

    }

    @Override
    public long countNotCancelByMember(String phone, Date start, Date end) {

        return orderMapper.countNotCancelByMemberPhoneWithDate(phone, start, end);
    }

    @Override
    public List<Order> queryNearBy(Double centerlng, Double centerlat, Double paidanKm) {

        SquareLocation squareLocation = Distance.returnSquarePoint(centerlng, centerlat, paidanKm);

        return orderMapper
            .selectBossNearBy(squareLocation.rightBottomLat, squareLocation.leftTopLat,
                squareLocation.leftTopLng, squareLocation.rightBottomLng);

    }

    @Override
    public Order findOneByDiverAndStatus(Long driverId, int status) {

        List<Order> content = orderMapper.selectByDriverWithStatus(driverId, status, null);

        if (!CollectionUtils.isEmpty(content)) {
            return content.get(0);
        }

        return null;
    }

    @Override
    public Order findLastedFinishedByDriver(final Long driverId) {

        List<Order> content = orderMapper
            .selectByDriverWithStatus(driverId, Order.ORDER_STATUS_FINISHED,
                Order.ORDER_STATUS_BAODAN);

        if (!CollectionUtils.isEmpty(content)) {
            return content.get(0);
        }

        return null;
    }

    @Override
    public Order findOneByDiverAndFinish(final Long driverId, final Long lastOrderId) {

        Setting setting = settingUtils.get();

        final int begin = setting.getWorkBegin();

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR_OF_DAY, -begin);
        calendar.set(Calendar.HOUR_OF_DAY, begin);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date start = calendar.getTime();

        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);

        Date end = calendar.getTime();

        return orderMapper.selectOneByDiverAndFinish(driverId, start, end, lastOrderId);

    }

    @Override
    public long countByDriverAndStatus(Long driverId, int status, Long lastOrderId) {

        return orderMapper.countByDriverAndStatus(driverId, status, lastOrderId);

    }

    @Override
    public List<Order> findByStatus(final Integer status) {

        return orderMapper.selectByCompanyWithStatus(null, status, null);

    }

    @Override
    public long countRefused() {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        if (!principal.isCompanyType()) {
            return orderMapper.countRefusedByCompany(principal.getCompanyId());
        } else {
            return orderMapper.countRefusedByCompany(null);
        }

    }

    @Override
    public Order findOneByDriverBeforeComplete(Long driverId, Long lastOrderId) {

        return orderMapper.selectOneByDriverBeforeComplete(driverId, lastOrderId);

    }

    @Override
    public Order findOneYestodayOrder() {

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -2);

        return orderMapper.selectOneYestodayOrder(calendar.getTime());

    }

    @Override
    public List<Order> findMonthOrder(Date start, Date end) {

        return orderMapper.selectMonthOrder(start, end);
    }

    @Override
    public List<Order> findByMemberId(Long id) {
        return orderMapper.selectByMemberId(id);
    }

    @Override
    public List<Order> findActiveByMember(Long id) {
        return orderMapper.selectActiveByMemberId(id);
    }

    @Override
    public long countActivedOrdersByDriver(Long id) {
        return orderMapper.countActivedOrdersByDriver(id);
    }

    @Override
    public Page<Map<String, Object>> daijialistData(String orderNumber, String clientPhone,
        String driverPhone,
        String companyName, String createOrderName, String[] orderType, String[] status,
        boolean warm, Date start,
        Date end, Date startFinish, Date endFinish) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        String likeOrderNumber = null;
        String likeClientPhone = null;
        String likeDriverPhone = null;
        String likeCompanyName = null;
        String likeCreateOrderName = null;
        if (StringUtils.isNotBlank(orderNumber)) {
            likeOrderNumber = "%" + orderNumber + "%";
        }
        if (StringUtils.isNotBlank(clientPhone)) {
            likeClientPhone = "%" + clientPhone + "%";
        }
        if (StringUtils.isNotBlank(driverPhone)) {
            likeDriverPhone = "%" + driverPhone + "%";
        }
        if (StringUtils.isNotBlank(companyName)) {
            likeCompanyName = "%" + companyName + "%";
        }
        if (StringUtils.isNotBlank(createOrderName)) {
            likeCreateOrderName = "%" + createOrderName + "%";
        }

        List<Integer> statusList = new ArrayList<Integer>();
        Boolean notpay = false;
        if (null != status && status.length > 0) {
            String statusStr = "";
            for (int i = 0; i < status.length; i++) {
                statusStr += status[i] + ",";
            }
            if (statusStr.contains("new")) {
                statusList.add(Order.ORDER_STATUS_NEW);
            }
            if (statusStr.contains("paidan")) {
                statusList.add(Order.ORDER_STATUS_YIPAIDAN);
            }
            if (statusStr.contains("busy")) {
                statusList.add(Order.ORDER_STATUS_BUSY);
            }
            if (statusStr.contains("notpay")) {
                notpay = true;
            }
            if (statusStr.contains("finish")) {
                statusList.add(Order.ORDER_STATUS_BAODAN);
            }
            if (statusStr.contains("cancel")) {
                statusList.add(Order.ORDER_STATUS_CANCELED);
            }
        }
        if (CollectionUtils.isEmpty(statusList)) {
            statusList = null;
        }

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -2);
        Date warmDate = calendar.getTime();

        List<Map<String, Object>> content = new ArrayList<Map<String, Object>>();
        long total = 0;

        List<Order> orderList = new ArrayList<Order>();
        if (!principal.isCompanyType()) {
            orderList = orderMapper
                .selectDaijiaList(null, principal.getCompanyId(), likeOrderNumber, likeClientPhone,
                    likeDriverPhone, likeCompanyName, likeCreateOrderName, orderType, statusList,
                    notpay, warm,
                    warmDate, start, end, startFinish, endFinish, Pager.getOffset(),
                    Pager.getLimit());
            total = orderMapper
                .countDaijiaList(null, principal.getCompanyId(), likeOrderNumber, likeClientPhone,
                    likeDriverPhone, likeCompanyName, likeCreateOrderName, orderType, statusList,
                    notpay, warm,
                    warmDate, start, end, startFinish, endFinish);
        } else {
            orderList = orderMapper
                .selectDaijiaList(null, null, likeOrderNumber, likeClientPhone, likeDriverPhone,
                    likeCompanyName, likeCreateOrderName, orderType, statusList, notpay, warm,
                    warmDate, start, end,
                    startFinish, endFinish, Pager.getOffset(), Pager.getLimit());
            total = orderMapper
                .countDaijiaList(null, null, likeOrderNumber, likeClientPhone, likeDriverPhone,
                    likeCompanyName, likeCreateOrderName, orderType, statusList, notpay, warm,
                    warmDate, start, end,
                    startFinish, endFinish);
        }
        if (total > 0) {
            DateFormat format = new SimpleDateFormat("MM/dd HH:mm");
            for (Order order : orderList) {
                order.setOrderStatuss(orderStatusMapper.selectByOrder(order.getId()));

                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", order.getId());
                map.put("status", order.getStatus());
                map.put("orderNumber", order.getOrderNumber());
                map.put("orderType", order.getOrderType());
                map.put("fromSource", order.getFromSource());
                map.put("serverTime", format.format(order.getServerTime()));
                if (null != order.getDaijiaTime()) {
                    map.put("chufaTime", format.format(order.getDaijiaTime()));
                } else {
                    map.put("chufaTime", "");
                }
                map.put("fromPlace", order.getFromPlace());
                if (null != order.getFinishTime()) {
                    map.put("finishTime", format.format(order.getFinishTime()));
                } else {
                    map.put("finishTime", "");
                }
                map.put("toPlace", order.getToPlace());
                map.put("mileage", order.getMileage());
                map.put("waitedTime", order.getWaitedTime());
                map.put("shouldCash", order.getShouldCash());
                map.put("createOrderName", order.getCreateOrderName());
                map.put("realCash", order.getRealCash());
                map.put("preAndAfterPayType", order.getPreAndAfterPayType());
                map.put("clientName", order.getClientName());
                map.put("userPhone", UseAllDataUtil
                    .useAllData(order.getUserPhone() != null ? order.getUserPhone()
                        : order.getClientPhone()));
                map.put("clientPhone", UseAllDataUtil.useAllData(order.getClientPhone()));
                map.put("driverRealName", order.getDriverRealName());
                map.put("driverPhone", UseAllDataUtil.useAllDataDriver(order.getDriverPhone()));
                map.put("carNumber", order.getCarNumber());
                map.put("memo", order.getMemo());
                map.put("hasVisited", order.isHasVisited());
                map.put("couponId", order.getCouponId());
                map.put("cancelContent", order.getCancelContent());
                map.put("hasHandelWarm", order.isHasHandelWarm());
                map.put("fromPlaceDetail", order.getFromPlaceDetail());
                map.put("toPlaceDetail", order.getToPlaceDetail());
                map.put("guoluMoney", order.getGuoluMoney());
                map.put("yuanchengMoney", order.getYuanchengMoney());
                map.put("otherMoney", order.getOtherMoney());
                map.put("justKilometres", order.getJustKilometres());
                map.put("justMoney", order.getJustMoney());

                Company thisCompany = companyMapper.selectByPrimaryKey(order.getCompanyId());
                map.put("companyAbbreviation", thisCompany.getAbbreviation());

                // 是否异常订单
                if (order.getStatus().equals(Order.ORDER_STATUS_FINISHED)
                    || order.getStatus().equals(Order.ORDER_STATUS_BAODAN)) {
                    if (!order.isHasHandelWarm()) {
                        if (order.getMileage() < 1 || order.getTravelTime() < 2) {
                            if (order.getCreated().getTime() > warmDate.getTime()) {
                                map.put("warm", true);
                                map.put("hasHandelWarm", order.isHasHandelWarm());
                            }
                        }
                    }
                }

                // 保险
                Insurance insurance = insuranceMapper.selectByOrderId(order.getId());
                if (null != insurance) {
                    map.put("insurance",
                        insurance.getPinganNo() + "#" + insurance.getInsuranceNo());
                }

                content.add(map);
            }
        }

        return new PageImpl<Map<String, Object>>(content, pageable, total);
    }

    @Override
    public List<Order> findActivedOrdersByDriver(Long driverId) {
        return orderMapper.selectActivedOrdersByDriver(driverId);
    }

    @Override
    public Map<String, Object> findByParams(Long clientId, Integer page, Integer rows) {

        Setting setting = settingUtils.get();

        Map<String, Object> mapData = new HashMap<String, Object>();
        Long total = 0L;
        List<Map<String, Object>> orderList = new ArrayList<Map<String, Object>>();
        Integer offset = (page - 1) * rows;
        Integer size = rows;
        List<Order> list = orderMapper.selectByParam(clientId, offset, size);
        total = orderMapper.countByParam(clientId);
        if (total > 0) {
            for (Order order : list) {
                if (order.getStatus() == 0 || order.getStatus() == 1 || order.getStatus() == 2
                    || order.getStatus() == 3
                    || order.getStatus() == 6) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    Long orderId = order.getId();
                    map.put("id", orderId);
                    map.put("companyId", order.getCompanyId());
                    Company company = companyMapper.selectByPrimaryKey(order.getCompanyId());
                    map.put("companyName", company.getAbbreviation());
                    map.put("orderNo", order.getOrderNumber());
                    map.put("passengerPhone", order.getClientPhone());
                    map.put("userPhone", order.getUserPhone());
                    map.put("startAddress", order.getFromPlace());
                    map.put("startLat", order.getClientLatitude());
                    map.put("startLng", order.getClientLongitude());
                    map.put("endAddress", order.getToPlace());
                    map.put("endLat", order.getToPlaceLatitude());
                    map.put("endLng", order.getToPlaceLongitude());
                    map.put("status", order.getStatus());
                    map.put("treatment", order.isTreatment());
                    map.put("createdTime", order.getCreated().getTime());
                    map.put("serverTime", order.getServerTime().getTime());
                    map.put("createdTime", order.getCreated().getTime());
                    map.put("review", order.isHasbeenRate());
                    map.put("budgetPay", order.getShouldCash());
                    map.put("mileage", order.getMileage());
                    map.put("runTime", order.getTravelTime());
                    map.put("realPay", order.getRealCash());
                    map.put("employId", order.getDriverId());
                    if (order.getDriverId() != null) {
                        Driver driver = driverMapper.selectByPrimaryKey(order.getDriverId());
                        if (driver != null) {
                            map.put("employName", driver.getName());
                            map.put("employPhone", driver.getPhone());
                            if (StringUtils.isNotBlank(driver.getPhoto())) {
                                map.put("employPhoto",
                                    setting.getWebUrl() + "/upload/driver/" + driver.getPhoto());
                            } else {
                                map.put("employPhoto", null);
                            }
                            map.put("employScore", driver.getStarLevel());
                            map.put("employCompanyId", driver.getCompanyId());
                            map.put("employNo", driver.getUsername());
                        }
                    }

                    map.put("startPrice", order.getStartPrice());
                    map.put("mileagePrice", order.getMileagePrice());
                    map.put("waitedPrice", order.getWaitedPrice());
                    map.put("travelPrice", order.getTravelPrice());
                    Rate rate = rateMapper.selectByOrderId(orderId);
                    if (rate != null) {
                        map.put("orderScore", rate.getStarLevel());
                        map.put("orderContent", rate.getContent());
                    }

                    // 详细状态
                    List<OrderStatus> orderStatuss = orderStatusMapper.selectByOrder(order.getId());
                    if (!CollectionUtils.isEmpty(orderStatuss)) {
                        Collections.sort(orderStatuss, new Comparator<OrderStatus>() {
                            public int compare(OrderStatus arg0, OrderStatus arg1) {
                                return arg1.getId().compareTo(arg0.getId());
                            }
                        });
                        List<OrderStatus> nowOrderStatuss = new ArrayList<OrderStatus>();
                        for (OrderStatus orderStatus : orderStatuss) {
                            if (orderStatus.getStatusType().equals(OrderStatus.StatusType.accept)) {
                                nowOrderStatuss.add(orderStatus);
                                break;
                            } else {
                                nowOrderStatuss.add(orderStatus);
                            }
                        }
                        if (!CollectionUtils.isEmpty(nowOrderStatuss)) {
                            for (OrderStatus orderStatus : nowOrderStatuss) {
                                if (orderStatus.getStatusType()
                                    .equals(OrderStatus.StatusType.daokehu)) {
                                    map.put("arriveTime", orderStatus.getHappened().getTime());
                                }
                                if (orderStatus.getStatusType()
                                    .equals(OrderStatus.StatusType.daijia2)) {
                                    map.put("startdriveTime", orderStatus.getHappened().getTime());
                                }
                            }
                        }
                    }

                    if (!map.containsKey("arriveTime")) {
                        map.put("arriveTime", null);
                    }

                    if (!map.containsKey("startdriveTime")) {
                        map.put("startdriveTime", null);
                    }

                    orderList.add(map);
                }
            }
        }
        mapData.put("orderList", orderList);
        mapData.put("total", total);
        return mapData;
    }

    @Override
    public Map<String, Object> findByParamsV5(Long clientId, Integer page, Integer rows) {

        Setting setting = settingUtils.get();

        Map<String, Object> mapData = new HashMap<String, Object>();
        Long total = 0L;
        List<Map<String, Object>> orderList = new ArrayList<Map<String, Object>>();
        Integer offset = (page - 1) * rows;
        Integer size = rows;
        List<Order> list = orderMapper.selectByParam(clientId, offset, size);
        total = orderMapper.countByParam(clientId);
        if (total > 0) {
            for (Order order : list) {
                if (order.getStatus() == 0 || order.getStatus() == 1 || order.getStatus() == 2
                    || order.getStatus() == 3
                    || order.getStatus() == 6) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    Long orderId = order.getId();
                    map.put("id", orderId);
                    map.put("companyId", order.getCompanyId());
                    Company company = companyMapper.selectByPrimaryKey(order.getCompanyId());
                    map.put("companyName", company.getAbbreviation());
                    map.put("orderNo", order.getOrderNumber());
                    map.put("passengerPhone", order.getClientPhone());
                    map.put("userPhone", order.getUserPhone());
                    map.put("startAddress", order.getFromPlace());
                    map.put("startLat", order.getClientLatitude());
                    map.put("startLng", order.getClientLongitude());
                    map.put("endAddress", order.getToPlace());
                    map.put("endLat", order.getToPlaceLatitude());
                    map.put("endLng", order.getToPlaceLongitude());
                    map.put("treatment", order.isTreatment());
                    map.put("createdTime", order.getCreated().getTime());
                    map.put("serverTime", order.getServerTime().getTime());
                    map.put("createdTime", order.getCreated().getTime());
                    map.put("review", order.isHasbeenRate());
                    map.put("budgetPay", order.getShouldCash());
                    map.put("mileage", order.getMileage());
                    map.put("runTime", order.getTravelTime());
                    map.put("realPay", order.getRealCash());
                    map.put("employId", order.getDriverId());
                    map.put("hasbeenRate", order.isHasbeenRate()); // 是否已评价
                    map.put("arrivePlaceDate", order.getArrivePlaceDate()); // 到达预约地时间

                    // 查询订单状态列表
                    List<OrderStatus> orderStatus_ = orderStatusService.findByOrder(order.getId());
                    map.put("orderStatus", orderStatus_); // 订单事件列表

                    // 判断订单状态
                    Long maxId = 0L;
                    for (OrderStatus status : orderStatus_) {
                        // 状态id,最大的id就是最新的订单状态
                        Long statusId = status.getId();
                        if (statusId >= maxId) {
                            maxId = statusId;
                        }
                    }
                    for (OrderStatus status : orderStatus_) {
                        Long statusId = status.getId();
                        if (statusId.equals(maxId) || statusId == maxId) {
                            StatusType type = status.getStatusType();
                            map.put("status", type);
                        }
                    }

                    if (order.getDriverId() != null) {
                        Driver driver = driverMapper.selectByPrimaryKey(order.getDriverId());
                        if (driver != null) {
                            map.put("employName", driver.getName());
                            map.put("employPhone", driver.getPhone());
                            if (StringUtils.isNotBlank(driver.getPhoto())) {
                                map.put("employPhoto",
                                    setting.getWebUrl() + "/upload/driver/" + driver.getPhoto());
                            } else {
                                map.put("employPhoto", null);
                            }
                            map.put("employScore", driver.getStarLevel());
                            map.put("employCompanyId", driver.getCompanyId());
                            map.put("employNo", driver.getUsername());
                        }
                    }

                    map.put("startPrice", order.getStartPrice());
                    map.put("mileagePrice", order.getMileagePrice());
                    map.put("waitedPrice", order.getWaitedPrice());
                    map.put("travelPrice", order.getTravelPrice());
                    Rate rate = rateMapper.selectByOrderId(orderId);
                    if (rate != null) {
                        map.put("orderScore", rate.getStarLevel());
                        map.put("orderContent", rate.getContent());
                    }

                    // 详细状态
                    List<OrderStatus> orderStatuss = orderStatusMapper.selectByOrder(order.getId());
                    if (!CollectionUtils.isEmpty(orderStatuss)) {
                        Collections.sort(orderStatuss, new Comparator<OrderStatus>() {
                            public int compare(OrderStatus arg0, OrderStatus arg1) {
                                return arg1.getId().compareTo(arg0.getId());
                            }
                        });
                        List<OrderStatus> nowOrderStatuss = new ArrayList<OrderStatus>();
                        for (OrderStatus orderStatus : orderStatuss) {
                            if (orderStatus.getStatusType().equals(OrderStatus.StatusType.accept)) {
                                nowOrderStatuss.add(orderStatus);
                                break;
                            } else {
                                nowOrderStatuss.add(orderStatus);
                            }
                        }
                        if (!CollectionUtils.isEmpty(nowOrderStatuss)) {
                            for (OrderStatus orderStatus : nowOrderStatuss) {
                                if (orderStatus.getStatusType()
                                    .equals(OrderStatus.StatusType.daokehu)) {
                                    map.put("arriveTime", orderStatus.getHappened().getTime());
                                }
                                if (orderStatus.getStatusType()
                                    .equals(OrderStatus.StatusType.daijia2)) {
                                    map.put("startdriveTime", orderStatus.getHappened().getTime());
                                }
                            }
                        }
                    }

                    if (!map.containsKey("arriveTime")) {
                        map.put("arriveTime", null);
                    }

                    if (!map.containsKey("startdriveTime")) {
                        map.put("startdriveTime", null);
                    }

                    orderList.add(map);
                }
            }
        }
        mapData.put("orderList", orderList);
        mapData.put("total", total);
        return mapData;
    }

    // 催单(更新上次催单时间)
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> hurryOrder(Long orderId) {
        Map<String, Object> map = new HashMap<String, Object>();

        Order order = orderMapper.selectByPrimaryKey(orderId);

        if (order != null) {
            if (null == order.getLasturge()) {
                orderMapper.updateCuidan(orderId);
                map.put("success", true);
                map.put("message", "消息已发出,管理员已经知道了");
                return map;
            }
            if (order.getStatus() == 0 || order.getStatus() == 1 || order.getStatus() == 2) {
                if ((System.currentTimeMillis() - order.getLasturge().getTime()) < (2 * 60 * 1000)) {
                    map.put("success", false);
                    if (order.getCreated().getTime() == order.getLasturge().getTime()) {
                        map.put("message", "我们正在为您寻找服务人员");
                    } else {
                        map.put("message", "订单刚催促过,两分钟内不能重复操作");
                    }
                    return map;
                } else {
                    int i = orderMapper.updateCuidan(orderId);
                    if (i == 1) {
                        map.put("success", true);
                        map.put("message", "消息已发出,管理员已经知道了");
                    } else {
                        map.put("success", false);
                        map.put("message", "催单失败");
                    }
                }
            } else {
                map.put("success", false);
                map.put("message", "订单已完成,或已销单,催促无效");
            }
        } else {
            map.put("success", false);
            map.put("message", "订单不存在");
        }
        return map;
    }

    @Override
    public List<Order> findCuidanOrders() {
        List<Order> oldList = new ArrayList<Order>();

        oldList = orderMapper.selectCuidan();

        List<Order> list = new ArrayList<Order>();

        if (oldList != null && oldList.size() != 0) {

            for (Order order : oldList) {
                if (list.size() == 10) {
                    break;
                }
                if (!order.getCreated().equals(order.getLasturge())) {
                    list.add(order);
                }
            }
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    public int closeCuidan(Long orderId) {
        return orderMapper.closeCuidan(orderId);
    }

    @Transactional(rollbackFor = Exception.class)
    public int updateCuidan(Long orderId) {
        return orderMapper.updateCuidan(orderId);
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Order> completeTaskNewV3(Order order, Passenger passenger, Driver driver,
        String completeType,
        String payType, BigDecimal hasPayed, boolean adminComplete) {

        Result<Order> result = new Result<Order>();

        if (!adminComplete) {
            int count = orderMapper.addFinishTime(order.getId());

            if (order.getStatus().equals(Order.ORDER_STATUS_FINISHED)
                || order.getStatus().equals(Order.ORDER_STATUS_BAODAN) || count == 0) {
                result.setSuccess(false);
                result.setErrorcode(
                    String.valueOf(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getCode()));
                result.setMessage(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getMessage());
                return result;
            }
        }

        // lock.lock();

        // try {

        order.setFinishTime(new Date());
        order.setStatus(Order.ORDER_STATUS_BAODAN);

        BigDecimal realCashRenBao = order.getRealCash();

        if (!"renBaoPay".equals(completeType)) {
            if (null != order.getOrderNoRenBao() && null != order.getCuponNoRenBao()) {
                if (null != order.getPreferentialType()) {
                    // 0898JHDJ1 == 38 0898JHDJ2 == 58 抵扣的金额
                    if (order.getPreferentialType().equals("0898JHDJ1")) {
                        realCashRenBao = realCashRenBao.add(new BigDecimal(38));
                    } else if (order.getPreferentialType().equals("0898JHDJ2")) {
                        realCashRenBao = realCashRenBao.add(new BigDecimal(58));
                    }
                }
            }
        }
        order.setRealCash(realCashRenBao);

        // 优惠券金额
        BigDecimal now_couponMoney = order.getCouponMoney();

        // 预付费金额
        BigDecimal prePayMoney = order.getShouldCash();//应收
        Double discount = order.getDiscount();//折扣
        /**
         * 对于应收款 如果有折扣就先折扣,否则就直接减去优惠券.
         */
        if (null != discount) {
            prePayMoney = prePayMoney // pre - pre * (1 - di/10) 四舍五入
                .subtract(prePayMoney
                    .multiply(BigDecimal.valueOf(1).subtract(BigDecimal.valueOf((discount / 10))))
                    .setScale(0, BigDecimal.ROUND_DOWN))
                .setScale(2, BigDecimal.ROUND_UP);
        } else {
            prePayMoney = prePayMoney.subtract(now_couponMoney);
        }

        // 结算应支付的金额
        BigDecimal afterPayMoney = BigDecimal.ZERO;
        if (null != order.getPrePayTypeDetail()) {
            if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                afterPayMoney = order.getRealCash().subtract(order.getGuoluMoney())
                    .subtract(now_couponMoney);
                if (afterPayMoney.doubleValue() < 0) {
                    afterPayMoney = BigDecimal.ZERO;
                }
                afterPayMoney = afterPayMoney.add(order.getGuoluMoney());
                afterPayMoney = afterPayMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
            } else {
                afterPayMoney = order.getRealCash();
                afterPayMoney = afterPayMoney.subtract(order.getGuoluMoney());
                afterPayMoney = afterPayMoney.subtract(now_couponMoney);
                if (afterPayMoney.doubleValue() < 0) {
                    afterPayMoney = BigDecimal.ZERO;
                }
                afterPayMoney = afterPayMoney.subtract(prePayMoney);
                afterPayMoney = afterPayMoney.add(order.getGuoluMoney());

                if (afterPayMoney.doubleValue() < 0) {
                    afterPayMoney = BigDecimal.ZERO;
                }
                afterPayMoney = afterPayMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
            }
        } else {
            afterPayMoney = order.getRealCash();
            afterPayMoney = afterPayMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
        }

        if ("clickPay".equals(completeType)) {
            if ("helppay".equals(payType)) {// 代付支付
                order.setAfterPayTypeDetail(Order.PayTypeDetails.helppay);
                order.setCashMoney(order.getCashMoney().add(afterPayMoney));
            } else if ("sign".equals(payType)) {// 签单支付
                order.setAfterPayTypeDetail(Order.PayTypeDetails.sign);
                order.setSignMoney(order.getSignMoney().add(afterPayMoney));
            } else if ("balance".equals(payType)) {// 余额支付
                order.setAfterPayTypeDetail(Order.PayTypeDetails.balance);
                order.setBalanceMoney(order.getBalanceMoney().add(afterPayMoney));
            }
        } else if ("onlinePay".equals(completeType)) {
            if ("alipay".equals(payType)) {// 支付宝支付
                order.setAfterPayTypeDetail(Order.PayTypeDetails.alipay);
                order.setAlipayMoney(order.getAlipayMoney().add(afterPayMoney));
            } else if ("weixin".equals(payType)) {
                order.setAfterPayTypeDetail(Order.PayTypeDetails.weixin);
                order.setWeixinMoney(order.getWeixinMoney().add(afterPayMoney));
            } else if ("unionpay".equals(payType)) {
                order.setAfterPayTypeDetail(Order.PayTypeDetails.unionpay);
                order.setUnionpayMoney(order.getUnionpayMoney().add(afterPayMoney));
            } else if ("bestpay".equals(payType)) {
                order.setAfterPayTypeDetail(Order.PayTypeDetails.bestpay);
                order.setBestpayMoney(order.getBestpayMoney().add(afterPayMoney));
            }
        } else if ("clickComplete".equals(completeType)) {
            if (null != order.getPrePayTypeDetail()) {
                if (order.getPrePayTypeDetail().equals(PayTypeDetails.sign)) {
                    order.setSignMoney(order.getRealCash());
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.balance)) {
                    order.setBalanceMoney(order.getRealCash());
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.alipay)) {
                    order.setAlipayMoney(order.getRealCash());
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.weixin)) {
                    order.setWeixinMoney(order.getRealCash());
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.unionpay)) {
                    order.setUnionpayMoney(order.getRealCash());
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.bestpay)) {
                    order.setBestpayMoney(order.getRealCash());
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_sign)) {
                    BigDecimal signMoney = order.getRealCash().subtract(order.getCouponMoney());
                    if (signMoney.doubleValue() < 0) {
                        signMoney = BigDecimal.ZERO;
                    }
                    order.setSignMoney(signMoney);
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_balance)) {
                    BigDecimal balanceMoney = order.getRealCash().subtract(order.getCouponMoney());
                    if (balanceMoney.doubleValue() < 0) {
                        balanceMoney = BigDecimal.ZERO;
                    }
                    order.setBalanceMoney(balanceMoney);
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_alipay)) {
                    BigDecimal alipayMoney = order.getRealCash().subtract(order.getCouponMoney());
                    if (alipayMoney.doubleValue() < 0) {
                        alipayMoney = BigDecimal.ZERO;
                    }
                    order.setAlipayMoney(alipayMoney);
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_weixin)) {
                    BigDecimal weixinMoney = order.getRealCash().subtract(order.getCouponMoney());
                    if (weixinMoney.doubleValue() < 0) {
                        weixinMoney = BigDecimal.ZERO;
                    }
                    order.setWeixinMoney(weixinMoney);
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_unionpay)) {
                    BigDecimal unionMoney = order.getRealCash().subtract(order.getCouponMoney());
                    if (unionMoney.doubleValue() < 0) {
                        unionMoney = BigDecimal.ZERO;
                    }
                    order.setUnionpayMoney(unionMoney);
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_bestpay)) {
                    BigDecimal bestpayMoney = order.getRealCash().subtract(order.getCouponMoney());
                    if (bestpayMoney.doubleValue() < 0) {
                        bestpayMoney = BigDecimal.ZERO;
                    }
                    order.setBestpayMoney(bestpayMoney);
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.helppay);
                    order.setCashMoney(BigDecimal.ZERO);
                }
            } else {
                order.setAfterPayTypeDetail(Order.PayTypeDetails.helppay);
                order.setCashMoney(BigDecimal.ZERO);
            }
        } else if ("renBaoPay".equals(completeType)) {
            order.setAfterPayTypeDetail(Order.PayTypeDetails.bestpay);
            order.setBestpayMoney(order.getBestpayMoney().add(afterPayMoney));
        }

        List<OrderStatus> orderStatuslist = orderStatusMapper.selectByOrder(order.getId());

        Date travelDate = null;
        if (!CollectionUtils.isEmpty(orderStatuslist)) {
            Collections.sort(orderStatuslist, new Comparator<OrderStatus>() {
                public int compare(OrderStatus arg0, OrderStatus arg1) {
                    return arg1.getId().compareTo(arg0.getId());
                }
            });

            for (OrderStatus os : orderStatuslist) {
                if (os.getStatusType().equals(StatusType.daijia2)) {
                    travelDate = os.getHappened();
                    break;
                }
            }
        }
        if (null == travelDate) {
            travelDate = new Date();
        }

        chartYearService.addDayRecord(order);// 增加统计

        OrderStatus os = new OrderStatus();
        os.setOrderId(order.getId());
        os.setStatusType(StatusType.wancheng);
        os.setHappened(order.getFinishTime());
        if (adminComplete) {
            Subject currentUser = SecurityUtils.getSubject();
            Principal principal = (Principal) currentUser.getPrincipal();
            os.setContent("管理员【" + principal.getUsername() + "】手动完工，行程时间为：" + order.getTravelTime()
                + "分钟，总等待时间为："
                + order.getWaitedTime() + "分钟,行驶里程为：" + order.getMileage() + "公里");
        } else {
            os.setContent(
                "【" + order.getDriverRealName() + "】到达目的地，并且结算完成，行程时间为：" + order.getTravelTime()
                    + "分钟，总等待时间为：" + order.getWaitedTime() + "分钟,行驶里程为：" + order.getMileage()
                    + "公里");
        }
        orderStatusMapper.insertRecord(os);

        // 客户相关
        if (null != passenger) {
            // 实际价格小于或等于预付费
            if ("clickComplete".equals(completeType)) {
                BigDecimal returnMoney = hasPayed.add(order.getCouponMoney())
                    .subtract(order.getRealCash());
                if (returnMoney.doubleValue() > hasPayed.doubleValue()) {
                    returnMoney = hasPayed;
                }

                if (returnMoney.doubleValue() != 0) {
                    if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                        passengerApi.createPassengerAccount(passenger, null, returnMoney,
                            PassengerAccount.PayType.RECHARGE_TYPE_RETURN,
                            PassengerAccount.OPERATING_SYS,
                            "订单实际价格小于预付费，返还余额", order.getId(), order.getOrderNumber(),
                            PassengerAccount.ORDER_TYPE_DAIJIA, null, true, false,
                            settingUtils.get());
                    } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                        Enterprise enterprise = passengerApi
                            .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                            .getResult();
                        if (null != enterprise) {
                            passengerApi.createEnterpriseAccount(enterprise, returnMoney,
                                PassengerAccount.PayType.RECHARGE_TYPE_RETURN,
                                PassengerAccount.OPERATING_SYS,
                                "订单实际价格小于预付费，返还余额", order.getId(), order.getOrderNumber(),
                                PassengerAccount.ORDER_TYPE_DAIJIA, null, true, false,
                                settingUtils.get());
                        }
                    }
                }
            } else if ("clickPay".equals(completeType)) {
                if ("helppay".equals(payType)) {// 如果是代付，服务人员收到现金，余额减钱
                    driver.setVirtual(driver.getVirtual().subtract(afterPayMoney));
                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                    driverPaymentsRecord.setMoney(afterPayMoney);
                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                    driverPaymentsRecord
                        .setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_HELPPAY);
                    driverPaymentsRecord.setDriverId(driver.getId());
                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                    driverPaymentsRecord.setOrderId(order.getId());
                    driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                    driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                    driverPaymentsRecord
                        .setMemo("为客户【" + passenger.getName() + "】代付" + afterPayMoney + "元。");
                    driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                    driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                    driverPaymentsRecord.setHappend(new Date());
                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                }
            }

            // 常用地址
            if (order.getHasToPlace()) {
                Result<PassengerAddress> result_address = passengerApi
                    .findPassengerToPlace(passenger.getId(),
                        PassengerAddress.TYPE_ADDRESS_OTHER, settingUtils.get());
                PassengerAddress passengerAddress = result_address.getResult();
                if (StringUtils.isNotBlank(order.getToPlace()) && null != order.getToPlaceLatitude()
                    && null != order.getToPlaceLongitude()) {
                    if (null == passengerAddress) {
                        passengerApi.addPassengerToPlace(passenger.getId(), order.getToPlace(),
                            order.getToPlaceLatitude(), order.getToPlaceLongitude(),
                            PassengerAddress.TYPE_ADDRESS_OTHER, settingUtils.get());
                    } else {
                        passengerApi
                            .updatePassengerToPlace(passenger.getId(), passengerAddress.getId(),
                                order.getToPlace(), order.getToPlaceLatitude(),
                                order.getToPlaceLongitude(),
                                PassengerAddress.TYPE_ADDRESS_OTHER, settingUtils.get());
                    }
                }
            }
            String memo = "";

            PassengerAccount.PayType ptype = null;
            // 结算记录
            if ("clickPay".equals(completeType) || "onlinePay".equals(completeType)) {
                realCashRenBao = afterPayMoney;
                if (null != order.getOrderNoRenBao() && null != order.getCuponNoRenBao()) {
                    if (null != order.getPreferentialType()) {
                        // 0898JHDJ1 == 38 0898JHDJ2 == 58 抵扣的金额
                        if (order.getPreferentialType().equals("0898JHDJ1")) {
                            realCashRenBao = realCashRenBao.subtract(new BigDecimal(38));
                        } else if (order.getPreferentialType().equals("0898JHDJ2")) {
                            realCashRenBao = realCashRenBao.subtract(new BigDecimal(58));
                        }
                    }
                }
                if (realCashRenBao.compareTo(BigDecimal.ZERO) == -1
                    || realCashRenBao.compareTo(BigDecimal.ZERO) == 0) {
                    realCashRenBao = BigDecimal.ZERO;
                }

                if (order.getAfterPayTypeDetail().equals(PayTypeDetails.helppay)) {
                    memo += "结算使用代付" + realCashRenBao.toString() + "元。";
                    ptype = PassengerAccount.PayType.PAYTYPE_CASH;
                }
                if (order.getAfterPayTypeDetail().equals(PayTypeDetails.sign)) {
                    memo += "结算使用签单支付" + realCashRenBao.toString() + "元。";
                    ptype = PassengerAccount.PayType.PAYTYPE_SIGN;
                }
                if (order.getAfterPayTypeDetail().equals(PayTypeDetails.balance)) {
                    memo += "结算使用余额支付" + realCashRenBao.toString() + "元。";
                    ptype = PassengerAccount.PayType.PAYTYPE_BALANCE;
                }
                if (order.getAfterPayTypeDetail().equals(PayTypeDetails.alipay)) {
                    memo += "结算使用支付宝支付" + realCashRenBao.toString() + "元。";
                    ptype = PassengerAccount.PayType.PAYTYPE_ALIPAY;
                }
                if (order.getAfterPayTypeDetail().equals(PayTypeDetails.weixin)) {
                    memo += "结算使用微信支付" + realCashRenBao.toString() + "元。";
                    ptype = PassengerAccount.PayType.PAYTYPE_WEIXIN;
                }
                if (order.getAfterPayTypeDetail().equals(PayTypeDetails.unionpay)) {
                    memo += "结算使用银联支付" + realCashRenBao.toString() + "元。";
                    ptype = PassengerAccount.PayType.PAYTYPE_UNIONPAY;
                }
                if (order.getAfterPayTypeDetail().equals(PayTypeDetails.bestpay)) {
                    memo += "结算使用翼支付支付" + realCashRenBao.toString() + "元。";
                    ptype = PassengerAccount.PayType.PAYTYPE_BESTPAY;
                }

                // 是否更新余额
                boolean updateBlance = false;
                if (order.getAfterPayTypeDetail().equals(PayTypeDetails.sign)
                    || order.getAfterPayTypeDetail().equals(PayTypeDetails.balance)) {
                    updateBlance = true;
                }

                PassengerAccount passengerAccount = null;

                if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                    Result<PassengerAccount> result_account = passengerApi
                        .createPassengerAccount(passenger, null,
                            realCashRenBao.negate(), ptype, PassengerAccount.OPERATING_SYS, memo,
                            order.getId(),
                            order.getOrderNumber(), PassengerAccount.ORDER_TYPE_DAIJIA, null,
                            updateBlance, true,
                            settingUtils.get());
                    passengerAccount = result_account.getResult();
                } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                    Enterprise enterprise = passengerApi
                        .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                        .getResult();
                    if (null != enterprise) {
                        Result<PassengerAccount> result_account = passengerApi
                            .createEnterpriseAccount(enterprise,
                                realCashRenBao.negate(), ptype, PassengerAccount.OPERATING_SYS,
                                memo, order.getId(),
                                order.getOrderNumber(), PassengerAccount.ORDER_TYPE_DAIJIA, null,
                                updateBlance, true,
                                settingUtils.get());
                        passengerAccount = result_account.getResult();
                    }
                }

                if (updateBlance) {
                    // 客户扣费短信
                    if (null != passengerAccount) {
                        if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                            MemberConsumedEvent consumedEvent = new MemberConsumedEvent(
                                passengerAccount, null);
                            applicationEventMulticaster.multicastEvent(consumedEvent);
                        } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                            MemberConsumedEvent consumedEvent = new MemberConsumedEvent(
                                passengerAccount,
                                passenger.getPhone());
                            applicationEventMulticaster.multicastEvent(consumedEvent);
                        }
                    }
                }

            } else if ("renBaoPay".equals(completeType)) {
                memo += "结算使用余额支付0元。";
                ptype = PassengerAccount.PayType.PAYTYPE_BALANCE;
                if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                    passengerApi.createPassengerAccount(passenger, null, BigDecimal.ZERO, ptype,
                        PassengerAccount.OPERATING_SYS, memo, order.getId(), order.getOrderNumber(),
                        PassengerAccount.ORDER_TYPE_DAIJIA, null, false, true, settingUtils.get());
                } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                    Enterprise enterprise = passengerApi
                        .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                        .getResult();
                    if (null != enterprise) {
                        passengerApi.createEnterpriseAccount(enterprise, BigDecimal.ZERO, ptype,
                            PassengerAccount.OPERATING_SYS, memo, order.getId(),
                            order.getOrderNumber(),
                            PassengerAccount.ORDER_TYPE_DAIJIA, null, false, true,
                            settingUtils.get());
                    }
                }
            }

            passenger.setMileage(passenger.getMileage() + order.getMileage());
            passenger.setDrivingNumberTimes(passenger.getDrivingNumberTimes() + 1);
            passengerApi.updatePersonal(passenger, settingUtils.get());

            if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                Enterprise enterprise = passengerApi
                    .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                    .getResult();
                if (null != enterprise) {
                    enterprise.setDrivingNumberTimes(enterprise.getDrivingNumberTimes() + 1);
                    passengerApi.updateEnterpriseInfo(enterprise, settingUtils.get());
                }
            }

            BigDecimal receiptMoney = order.getRealCash().subtract(order.getGuoluMoney())
                .subtract(order.getCouponMoney());
            if (receiptMoney.doubleValue() > 0) {
                passengerApi.createReceipt(passenger, receiptMoney.negate(), settingUtils.get());
            }

        }

        // 订单财务记录
        OrderFinishedInfo orderFinishedInfo = new OrderFinishedInfo();
        orderFinishedInfo.setOrderId(order.getId());
        orderFinishedInfo.setOrderNumber(order.getOrderNumber());
        orderFinishedInfo.setFinishTime(order.getFinishTime());
        orderFinishedInfo.setCreateTime(order.getCreated());
        orderFinishedInfo.setClientId(order.getClientId());
        orderFinishedInfo.setClientPhone(order.getClientPhone());
        orderFinishedInfo.setDriverId(order.getDriverId());
        orderFinishedInfo.setCompanyId(order.getCompanyId());
        orderFinishedInfo.setPrePayTypeDetail(order.getPrePayTypeDetail());
        orderFinishedInfo.setAfterPayTypeDetail(order.getAfterPayTypeDetail());
        orderFinishedInfo.setShouldCash(order.getShouldCash());
        orderFinishedInfo.setRealCash(order.getRealCash());
        orderFinishedInfo.setCouponMoney(order.getCouponMoney());
        orderFinishedInfo.setCashMoney(order.getCashMoney());
        orderFinishedInfo.setSignMoney(order.getSignMoney());
        orderFinishedInfo.setBalanceMoney(order.getBalanceMoney());
        orderFinishedInfo.setAlipayMoney(order.getAlipayMoney());
        orderFinishedInfo.setWeixinMoney(order.getWeixinMoney());
        orderFinishedInfo.setGuoluMoney(order.getGuoluMoney());
        orderFinishedInfo.setYuanchengMoney(order.getYuanchengMoney());
        orderFinishedInfo.setOtherMoney(order.getOtherMoney());
        // 信息费,可能是接单产生
        List<DriverPaymentsRecord> infoFeeList = driverPaymentsRecordMapper
            .selectByRecordTypeAndOrder(
                DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI, order.getId(),
                DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
        if (!CollectionUtils.isEmpty(infoFeeList)) {
            for (DriverPaymentsRecord driverPaymentsRecord : infoFeeList) {
                if (driverPaymentsRecord.getInfoFeeType()
                    .equals(DriverPaymentsRecord.INFOFEE_TYPE_INFO)) {
                    orderFinishedInfo.setInfoFee(
                        orderFinishedInfo.getInfoFee().add(driverPaymentsRecord.getMoney()));
                } else if (driverPaymentsRecord.getInfoFeeType()
                    .equals(DriverPaymentsRecord.INFOFEE_TYPE_DJX)) {
                    orderFinishedInfo.setDjxFee(
                        orderFinishedInfo.getDjxFee().add(driverPaymentsRecord.getMoney()));
                } else if (driverPaymentsRecord.getInfoFeeType()
                    .equals(DriverPaymentsRecord.INFOFEE_TYPE_YWX)) {
                    orderFinishedInfo.setYwxFee(
                        orderFinishedInfo.getYwxFee().add(driverPaymentsRecord.getMoney()));
                }
            }
        }
        // 订单财务记录

        BigDecimal realCash = order.getRealCash().subtract(order.getGuoluMoney());
        String wxMemo = "";

        // 优惠劵是否参与提成
        Setting setting = settingUtils.get();
        boolean couponTicheng = setting.isCouponTicheng();

        // 是否使用了优惠劵
        if (order.getCouponMoney().doubleValue() > 0) {
            if (!couponTicheng) {
                realCash = realCash.subtract(order.getCouponMoney());
                if (realCash.compareTo(BigDecimal.ZERO) == -1) {
                    realCash = BigDecimal.ZERO;
                }
            }
        }

        // 客户经理提成
        WeixinManagerXOrder wxo = weixinManagerXOrderMapper.selectByOrderId(order.getId());
        BigDecimal wx_driver_money = BigDecimal.ZERO;// 客户经理提成金额 司机承担金额
        BigDecimal wx_company_money = BigDecimal.ZERO;// 客户经理提成金额 公司承担金额
        BigDecimal wxMoney = BigDecimal.ZERO;
        WeixinManager weixinManager = null;
        if (null != wxo) {
            wxo.setFinishedTime(order.getFinishTime());
            weixinManager = weixinManagerMapper.selectByPrimaryKey(wxo.getManagerId());
            if (null != weixinManager) {
                BigDecimal money = BigDecimal.ZERO;
                if (weixinManager.getWeixinManagerMoneyType()
                    .equals(WeixinManagerMoneyType.guding)) {
                    if (realCash.compareTo(weixinManager.getFixedMoney()) == -1) {
                        money = realCash;
                        wxo.setMoney(money);
                    } else {
                        money = weixinManager.getFixedMoney();
                        wxo.setMoney(money);
                    }
                } else if (weixinManager.getWeixinManagerMoneyType()
                    .equals(WeixinManagerMoneyType.bili)) {
                    money = realCash.multiply(weixinManager.getRatioMoney())
                        .divide(new BigDecimal(100));
                    wxo.setMoney(money);
                }
                weixinManagerMapper.updateVirtual(weixinManager.getId(), money);

                wxMoney = money;

                wxMemo = "客户经理经理提成" + money + "元。";

                WeixinManagerPayments weixinManagerPayments = new WeixinManagerPayments();
                weixinManagerPayments.setManagerId(weixinManager.getId());
                weixinManagerPayments.setOrderId(order.getId());
                weixinManagerPayments.setOrderNumber(order.getOrderNumber());
                weixinManagerPayments.setMoney(money);
                weixinManagerPayments.setAfterVirtual(weixinManager.getVirtual().add(money));
                weixinManagerPayments
                    .setRecordType(WeixinManagerPayments.RECORD_TYPE_RECHARGE_ORDER);
                weixinManagerPaymentsMapper.insertRecord(weixinManagerPayments);

                Integer feeAllocation = weixinManager.getFeeAllocation();
                if (null != feeAllocation) {
                    wx_company_money = money.multiply(new BigDecimal(feeAllocation))
                        .divide(new BigDecimal(100));
                    wx_driver_money = money.subtract(wx_company_money);
                }
            }
            weixinManagerXOrderMapper.updateByPrimaryKey(wxo);
        }

        // 订单财务记录
        orderFinishedInfo.setWxManagerMoney(wxMoney);
        // 订单财务记录

        // 服务人员设为空闲
        boolean companyGetAll = false;// 公司是否的全部
        boolean employWxPayed = true;// 司机是否需要承担客户经理提成

        DateFormat format = new SimpleDateFormat("yyyyMMdd");

        StringBuilder sbmemo = new StringBuilder();
        sbmemo.append("订单【" + order.getOrderNumber() + "】，客户【" + order.getClientName() + "(" + order
            .getClientPhone()
            + ")】，");

        // 预支付备注
        if (null != order.getPrePayTypeDetail()) {
            if (order.getPrePayTypeDetail().equals(PayTypeDetails.sign)) {
                sbmemo.append("预付费：签单支付（" + prePayMoney + "元）。");
            } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.balance)) {
                sbmemo.append("预付费：余额支付（" + prePayMoney + "元）。");
            } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.alipay)) {
                sbmemo.append("预付费：支付宝支付（" + prePayMoney + "元）。");
            } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.weixin)) {
                sbmemo.append("预付费：微信支付（" + prePayMoney + "元）。");
            } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.unionpay)) {
                sbmemo.append("预付费：银联支付（" + prePayMoney + "元）。");
            } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.bestpay)) {
                sbmemo.append("预付费：翼支付支付（" + prePayMoney + "元）。");
            } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_sign)) {
                if (null == discount) {
                    sbmemo.append(
                        "预付费：签单支付（" + prePayMoney + "元）,并且使用了" + order.getCouponMoney().toString()
                            + "元优惠券。");
                } else {
                    sbmemo.append(
                        "预付费：签单支付（" + prePayMoney + "元）,并且使用了" + discount.toString() + "折优惠券。");
                }
            } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_balance)) {
                if (null == discount) {
                    sbmemo.append(
                        "预付费：余额支付（" + prePayMoney + "元）,并且使用了" + order.getCouponMoney().toString()
                            + "元优惠券。");
                } else {
                    sbmemo.append(
                        "预付费：余额支付（" + prePayMoney + "元）,并且使用了" + discount.toString() + "折优惠券。");
                }
            } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_alipay)) {
                if (null == discount) {
                    sbmemo.append(
                        "预付费：支付宝支付（" + prePayMoney + "元）,并且使用了" + order.getCouponMoney().toString()
                            + "元优惠券。");
                } else {
                    sbmemo.append(
                        "预付费：支付宝支付（" + prePayMoney + "元）,并且使用了" + discount.toString() + "折优惠券。");
                }
            } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_weixin)) {
                if (null == discount) {
                    sbmemo.append(
                        "预付费：微信支付（" + prePayMoney + "元）,并且使用了" + order.getCouponMoney().toString()
                            + "元优惠券。");
                } else {
                    sbmemo.append(
                        "预付费：微信支付（" + prePayMoney + "元）,并且使用了" + discount.toString() + "折优惠券。");
                }
            } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_unionpay)) {
                if (null == discount) {
                    sbmemo.append(
                        "预付费：银联支付（" + prePayMoney + "元）,并且使用了" + order.getCouponMoney().toString()
                            + "元优惠券。");
                } else {
                    sbmemo.append(
                        "预付费：银联支付（" + prePayMoney + "元）,并且使用了" + discount.toString() + "折优惠券。");
                }
            } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_bestpay)) {
                if (null == discount) {
                    sbmemo.append(
                        "预付费：翼支付支付（" + prePayMoney + "元）,并且使用了" + order.getCouponMoney().toString()
                            + "元优惠券。");
                } else {
                    sbmemo.append(
                        "预付费：翼支付支付（" + prePayMoney + "元）,并且使用了" + discount.toString() + "折优惠券。");
                }
            } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                if (null == discount) {
                    sbmemo.append("使用了" + order.getCouponMoney().toString() + "元优惠券。");
                } else {
                    sbmemo.append("使用了" + discount.toString() + "折优惠券。");
                }
            }

            if (couponTicheng) {
                sbmemo.append("优惠劵参与提成计算。");
            } else {
                sbmemo.append("优惠劵不参与提成计算。");
            }
        }

        // 后支付备注
        if (null != order.getAfterPayTypeDetail()) {
            if (order.getAfterPayTypeDetail().equals(PayTypeDetails.helppay)) {
                sbmemo.append("结算加收：代付（" + afterPayMoney + "元）。");
            } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.sign)) {
                sbmemo.append("结算加收：签单支付（" + afterPayMoney + "元）。");
            } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.balance)) {
                sbmemo.append("结算加收：余额支付（" + afterPayMoney + "元）。");
            } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.alipay)) {
                sbmemo.append("结算加收：支付宝支付（" + afterPayMoney + "元）。");
            } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.weixin)) {
                sbmemo.append("结算加收：微信支付（" + afterPayMoney + "元）。");
            } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.unionpay)) {
                sbmemo.append("结算加收：银联支付（" + afterPayMoney + "元）。");
            } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.bestpay)) {
                sbmemo.append("结算加收：翼支付支付（" + afterPayMoney + "元）。");
            }
        }

        if (null != driver) {
            driver.setTodayOrders(driver.getTodayOrders() + 1);
            driver.setMonthOrders(driver.getMonthOrders() + 1);
            driver.setDriveTimes(driver.getDriveTimes() + 1);
            driverMapper.updateWhenFinishOrderByKey(driver);

            if (adminComplete) {
                if (!driver.getStatus().equals(Driver.DRIVER_OFFLINE)) {
                    driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null,
                        driver.getId());
                }
            }

            Company company = companyMapper.selectByPrimaryKey(driver.getCompanyId());
            Company orderCompany = companyMapper.selectByPrimaryKey(order.getCompanyId());

            // 扣费 提成
            if (null != driver.getType() && Driver.DRIVER_TYPR_PARTTIME.equals(driver.getType())) {

                DriverChoseLevel driverChoseLevel = null;

                // 司机补单单独提成
                boolean bd = false;
                DriverLevel bd_driverLevel = null;
                if (order.getOrderType().equals(Order.ORDER_TYPE_BUDAN)) {
                    if (null != company.getBdLevelId()) {
                        bd_driverLevel = driverLevelMapper
                            .selectByPrimaryKey(company.getBdLevelId());
                        if (null != bd_driverLevel) {
                            bd = true;
                            driverChoseLevel = new DriverChoseLevel();
                            driverChoseLevel.setDriverlevelId(bd_driverLevel.getId());
                        }
                    }
                }

                if (null == driverChoseLevel) {
                    driverChoseLevel = driverChoseLevelMapper
                        .selectByDriverAndCompany(driver.getId(),
                            order.getCompanyId());
                }

                if (null != driverChoseLevel) {

                    DriverLevel driverLevel = null;

                    if (driverChoseLevel.getDriverlevelId() == 0) {// 始终使用本公司提成
                        DriverChoseLevel driverChoseLevel2 = driverChoseLevelMapper
                            .selectByDriverAndCompany(driver.getId(), driver.getCompanyId());
                        if (null != driverChoseLevel2) {
                            driverLevel = driverLevelMapper
                                .selectByPrimaryKey(driverChoseLevel2.getDriverlevelId());
                        }
                    } else {
                        driverLevel = driverLevelMapper
                            .selectByPrimaryKey(driverChoseLevel.getDriverlevelId());
                    }

                    DriverLevelDetail detail = null;
                    DriverLevelMoneyTimeDetail moneyTimeDetail = null;

                    if (null != driverLevel) {
                        if (driverLevel.getType().equals(0)) {
                            driverLevel.setDriverLevelDetails(
                                driverLevelDetailMapper.selectByDriverLevel(driverLevel.getId()));
                            if (driverLevel.getTimePoint().equals(TimePoint.serviceTime)) {
                                detail = driverLevel.getDeatil(order.getServerTime());
                            } else if (driverLevel.getTimePoint().equals(TimePoint.startDrive)) {
                                detail = driverLevel.getDeatil(travelDate);
                            } else if (driverLevel.getTimePoint().equals(TimePoint.finishTime)) {
                                detail = driverLevel.getDeatil(order.getFinishTime());
                            }
                        } else if (driverLevel.getType().equals(1)) {
                            driverLevel.setDriverLevelMoneyTimeDetails(
                                driverLevelMoneyTimeDetailMapper
                                    .selectByDriverLevel(driverLevel.getId()));
                            if (driverLevel.getTimePoint().equals(TimePoint.serviceTime)) {
                                moneyTimeDetail = driverLevel
                                    .getMoneyTimeDeatil(order.getServerTime());
                            } else if (driverLevel.getTimePoint().equals(TimePoint.startDrive)) {
                                moneyTimeDetail = driverLevel.getMoneyTimeDeatil(travelDate);
                            } else if (driverLevel.getTimePoint().equals(TimePoint.finishTime)) {
                                moneyTimeDetail = driverLevel
                                    .getMoneyTimeDeatil(order.getFinishTime());
                            }
                        }
                    }

                    if (null != detail) {

                        BigDecimal money = BigDecimal.ZERO;
                        BigDecimal companyMoney = BigDecimal.ZERO;

                        if (bd) {
                            sbmemo.append("补单使用单独提成方式。");
                        }

                        if (detail.getDriverLevelType().equals(DriverLevelType.ticheng)) {
                            if (realCash.compareTo(detail.getMinCommission()) == -1) {
                                money = realCash.subtract(detail.getLowCommission()).setScale(2,
                                    BigDecimal.ROUND_HALF_UP);
                                companyMoney = detail.getLowCommission();
                                if (money.doubleValue() < 0) {
                                    money = BigDecimal.ZERO;
                                    companyMoney = realCash;
                                }
                                sbmemo.append("按照【低于" + detail.getMinCommission() + "元公司得" + detail
                                    .getLowCommission()
                                    + "元】方式，服务人员得" + money + "元。");
                            } else {
                                money = realCash
                                    .multiply(new BigDecimal(100).subtract(detail.getCommission()))
                                    .divide(new BigDecimal(100));
                                companyMoney = realCash.subtract(money);
                                sbmemo.append("按照【" + detail.getCommission() + "%公司所得】提成方式。");
                            }
                        } else if (detail.getDriverLevelType().equals(DriverLevelType.guding)) {
                            if (realCash.compareTo(detail.getMinMoney()) == -1) {
                                money = realCash.subtract(detail.getLowMoney())
                                    .setScale(2, BigDecimal.ROUND_HALF_UP);
                                companyMoney = detail.getLowMoney();
                                if (money.doubleValue() < 0) {
                                    money = BigDecimal.ZERO;
                                    companyMoney = realCash;
                                }
                                sbmemo.append(
                                    "按照【低于" + detail.getMinMoney() + "元公司得" + detail.getLowMoney()
                                        + "元】方式，服务人员得" + money + "元。");
                            } else {

                                sbmemo.append("按照【" + detail.getMoney() + "元公司所得】提成方式。");

                                if (realCash.compareTo(detail.getMoney()) == -1) {
                                    money = BigDecimal.ZERO;
                                    companyMoney = realCash;
                                } else {
                                    money = realCash.subtract(detail.getMoney());
                                    companyMoney = detail.getMoney();
                                }

                            }
                        }

                        driver.setVirtual(driver.getVirtual().add(money));
                        driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                        DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                        driverPaymentsRecord.setMoney(money);
                        driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                        driverPaymentsRecord
                            .setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                        driverPaymentsRecord.setDriverId(driver.getId());
                        driverPaymentsRecord.setDriverRealName(driver.getRealname());
                        driverPaymentsRecord.setDriverUserName(driver.getUsername());
                        driverPaymentsRecord.setDriverPhone(driver.getPhone());
                        driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                        driverPaymentsRecord.setOrderId(order.getId());
                        driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                        driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                        driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                        driverPaymentsRecord.setMemo(sbmemo.toString() + wxMemo);
                        driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                        driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                        driverPaymentsRecord.setHappend(new Date());
                        driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                        // 公司财务
                        String companyMemo =
                            "订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                                + order.getOrderNumber() + "</a>】收入。";

                        FinancialRecord financialRecord = new FinancialRecord();
                        StringBuilder sb = new StringBuilder();
                        sb.append(OrderNumberConfig.FINANCIAL_ORDER);// 订单金额
                        sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);// 对象 客户
                        sb.append(format.format(new Date()));// 年月日时间
                        sb.append(OrderNumberConfig
                            .padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                        financialRecord.setCode(sb.toString());
                        financialRecord.setCompanyId(company.getId());
                        financialRecord.setCompanyName(company.getAbbreviation());
                        financialRecord.setOrderCompanyId(orderCompany.getId());
                        financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                        financialRecord.setMemo(companyMemo + driverPaymentsRecord.getMemo());
                        financialRecord.setMoney(companyMoney);
                        financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                        if (StringUtils.isNotBlank(order.getClientName())) {
                            financialRecord.setWho(order.getClientName());
                        } else {
                            financialRecord.setWho(order.getClientPhone());
                        }
                        financialRecord.setOrderId(order.getId());
                        financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                        financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                        financialRecordMapper.insertRecord(financialRecord);

                        // 订单财务记录
                        orderFinishedInfo.setDriverMoney(money);
                        orderFinishedInfo.setCompanyMoney(companyMoney);
                        // 订单财务记录

                    } else if (null != moneyTimeDetail) {// 复杂提成

                        BigDecimal money = BigDecimal.ZERO;
                        BigDecimal companyMoney = BigDecimal.ZERO;// 公司所得金额

                        if (!CollectionUtils
                            .isEmpty(moneyTimeDetail.getDriverLevelMoneyDetails())) {

                            for (DriverLevelMoneyDetail dlmd : moneyTimeDetail
                                .getDriverLevelMoneyDetails()) {
                                if (realCash.doubleValue() >= dlmd.getFromMoney().doubleValue()) {

                                    BigDecimal _money = BigDecimal.ZERO;
                                    if (realCash.doubleValue() >= dlmd.getToMoney().doubleValue()) {
                                        _money = dlmd.getToMoney().subtract(dlmd.getFromMoney());
                                    } else {
                                        _money = realCash.subtract(dlmd.getFromMoney());
                                    }

                                    if (dlmd.getDriverLevelMoneyType()
                                        .equals(DriverLevelMoneyType.guding)) {// 固定
                                        BigDecimal tcMoney = dlmd.getMoney()
                                            .multiply(new BigDecimal(
                                                (int) (_money.doubleValue() / dlmd.getMoneyUnit()
                                                    .doubleValue())));
                                        companyMoney = companyMoney.add(tcMoney);
                                    } else if (dlmd.getDriverLevelMoneyType()
                                        .equals(DriverLevelMoneyType.ticheng)) {// 比例
                                        BigDecimal tcMoney = _money.multiply(dlmd.getCommission())
                                            .divide(new BigDecimal(100));
                                        companyMoney = companyMoney.add(tcMoney);
                                    }
                                }
                            }
                        }

                        if (realCash.compareTo(companyMoney) == -1) {
                            companyMoney = realCash;
                            money = BigDecimal.ZERO;
                            sbmemo.append("金额不足，公司实际提成" + companyMoney + "元。");
                        } else {
                            money = realCash.subtract(companyMoney);
                        }

                        driver.setVirtual(driver.getVirtual().add(money));
                        driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                        DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                        driverPaymentsRecord.setMoney(money);
                        driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                        driverPaymentsRecord
                            .setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                        driverPaymentsRecord.setDriverId(driver.getId());
                        driverPaymentsRecord.setDriverRealName(driver.getRealname());
                        driverPaymentsRecord.setDriverUserName(driver.getUsername());
                        driverPaymentsRecord.setDriverPhone(driver.getPhone());
                        driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                        driverPaymentsRecord.setOrderId(order.getId());
                        driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                        driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                        driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                        driverPaymentsRecord.setMemo(sbmemo.toString() + wxMemo);
                        driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                        driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                        driverPaymentsRecord.setHappend(new Date());
                        driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                        // 公司财务
                        String companyMemo =
                            "订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                                + order.getOrderNumber() + "</a>】收入。";

                        FinancialRecord financialRecord = new FinancialRecord();
                        StringBuilder sb = new StringBuilder();
                        sb.append(OrderNumberConfig.FINANCIAL_ORDER);// 订单金额
                        sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);// 对象 客户
                        sb.append(format.format(new Date()));// 年月日时间
                        sb.append(OrderNumberConfig
                            .padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                        financialRecord.setCode(sb.toString());
                        financialRecord.setCompanyId(company.getId());
                        financialRecord.setCompanyName(company.getAbbreviation());
                        financialRecord.setOrderCompanyId(orderCompany.getId());
                        financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                        financialRecord.setMemo(companyMemo + driverPaymentsRecord.getMemo());
                        financialRecord.setMoney(companyMoney);
                        financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                        if (StringUtils.isNotBlank(order.getClientName())) {
                            financialRecord.setWho(order.getClientName());
                        } else {
                            financialRecord.setWho(order.getClientPhone());
                        }
                        financialRecord.setOrderId(order.getId());
                        financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                        financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                        financialRecordMapper.insertRecord(financialRecord);

                        // 订单财务记录
                        orderFinishedInfo.setDriverMoney(money);
                        orderFinishedInfo.setCompanyMoney(companyMoney);
                        // 订单财务记录

                    } else {
                        companyGetAll = true;
                        // 订单财务记录
                        orderFinishedInfo.setDriverMoney(BigDecimal.ZERO);
                        orderFinishedInfo.setCompanyMoney(order.getRealCash()
                            .subtract(orderFinishedInfo.getWxManagerMoney())
                            .subtract(order.getGuoluMoney()));
                        // 订单财务记录
                    }

                } else {
                    companyGetAll = true;
                    // 订单财务记录
                    orderFinishedInfo.setDriverMoney(BigDecimal.ZERO);
                    orderFinishedInfo.setCompanyMoney(order.getRealCash()
                        .subtract(orderFinishedInfo.getWxManagerMoney())
                        .subtract(order.getGuoluMoney()));
                    // 订单财务记录
                }
            } else {
                companyGetAll = true;

                // 司机不存在或全职不承担费用
                employWxPayed = false;

                // 订单财务记录
                orderFinishedInfo.setDriverMoney(BigDecimal.ZERO);
                orderFinishedInfo.setCompanyMoney(
                    order.getRealCash().subtract(orderFinishedInfo.getWxManagerMoney())
                        .subtract(order.getGuoluMoney()));
                // 订单财务记录
            }

            // 公司得全部
            if (companyGetAll) {
                String companyMemo =
                    "订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                        + order.getOrderNumber() + "</a>】收入。";

                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb = new StringBuilder();
                sb.append(OrderNumberConfig.FINANCIAL_ORDER);// 订单金额
                sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);// 对象 客户
                sb.append(format.format(new Date()));// 年月日时间
                sb.append(
                    OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                financialRecord.setCode(sb.toString());
                financialRecord.setCompanyId(company.getId());
                financialRecord.setCompanyName(company.getAbbreviation());
                financialRecord.setOrderCompanyId(orderCompany.getId());
                financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                financialRecord.setMemo(companyMemo + sbmemo.toString() + wxMemo);
                financialRecord.setMoney(realCash.subtract(wxMoney));
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                if (StringUtils.isNotBlank(order.getClientName())) {
                    financialRecord.setWho(order.getClientName());
                } else {
                    financialRecord.setWho(order.getClientPhone());
                }
                financialRecord.setOrderId(order.getId());
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                financialRecordMapper.insertRecord(financialRecord);
            }

            // 司机承担客户经理提成
            if (wx_driver_money.doubleValue() > 0) {
                if (employWxPayed) {
                    driver.setVirtual(driver.getVirtual().subtract(wx_driver_money));
                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                    driverPaymentsRecord.setMoney(wx_driver_money);
                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                    driverPaymentsRecord.setRecordType(DriverPaymentsRecord.WX_MANAGER_FEE);
                    driverPaymentsRecord.setDriverId(driver.getId());
                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                    driverPaymentsRecord.setOrderId(order.getId());
                    driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                    driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                    driverPaymentsRecord
                        .setMemo("司机承担客户经理提成" + wx_driver_money + "元，公司承担客户经理提成" + wx_company_money
                            + "元");
                    driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                    driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                    driverPaymentsRecord.setHappend(new Date());
                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);
                }
            }

            // 公司承担客户经理提成
            if (wx_company_money.doubleValue() > 0) {
                String memo =
                    "公司承担客户经理提成" + wx_company_money + "元，司机承担客户经理提成" + wx_driver_money + "元";
                if (!employWxPayed) {
                    // 司机不存在或全职，公司承担全部
                    wx_company_money = wx_company_money.add(wx_driver_money);
                    memo = "公司承担所有客户经理提成" + wx_company_money + "元";
                }
                // 公司财务
                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb = new StringBuilder();
                sb.append(OrderNumberConfig.FINANCIAL_MANAGERTIXIAN);// 承担提成
                sb.append(OrderNumberConfig.FINANCIAL_WHO_MANAGER);// 对象 客户
                sb.append(format.format(new Date()));// 年月日时间
                sb.append(
                    OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                financialRecord.setCode(sb.toString());
                financialRecord.setCompanyId(company.getId());
                financialRecord.setCompanyName(company.getAbbreviation());
                financialRecord.setOrderCompanyId(orderCompany.getId());
                financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                financialRecord.setMemo(memo);
                financialRecord.setMoney(wx_company_money.negate());
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                financialRecord.setWho(weixinManager.getName());
                financialRecord.setOrderId(order.getId());
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_MANAGERFEE);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                financialRecordMapper.insertRecord(financialRecord);
            }

            // 过路费
            BigDecimal fee = order.getGuoluMoney();
            if (fee.doubleValue() > 0) {
                driver.setVirtual(driver.getVirtual().add(fee));
                driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                driverPaymentsRecord.setMoney(fee);
                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER_GUOLU);
                driverPaymentsRecord.setDriverId(driver.getId());
                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                driverPaymentsRecord.setOrderId(order.getId());
                driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                driverPaymentsRecord
                    .setMemo("订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                        + order.getOrderNumber() + "</a>】过路费");
                driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                driverPaymentsRecord.setHappend(new Date());
                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);
            }

            if (null != orderCompany.getInfoFeeType()
                && orderCompany.getInfoFeeType().compareTo(Company.InfoFeeType.finishTask) == 0) {
                // 信息费
                if (orderCompany.getInfoFee().doubleValue() != 0) {
                    driver.setVirtual(driver.getVirtual().subtract(orderCompany.getInfoFee()));
                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                    // 扣费记录
                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                    driverPaymentsRecord.setMoney(orderCompany.getInfoFee());
                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                    driverPaymentsRecord
                        .setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                    driverPaymentsRecord.setInfoFeeType(DriverPaymentsRecord.INFOFEE_TYPE_INFO);
                    driverPaymentsRecord.setDriverId(driver.getId());
                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                    driverPaymentsRecord.setOrderId(order.getId());
                    driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                    driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                    driverPaymentsRecord.setMemo("扣除公司所得信息费" + orderCompany.getInfoFee() + "元。");
                    driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                    driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                    driverPaymentsRecord.setHappend(new Date());
                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                    // 财务记录（保险费）
                    Company mainCompany = companyMapper.selectMainCompany();
                    DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                    FinancialRecord financialRecord = new FinancialRecord();
                    StringBuilder sb_f = new StringBuilder();
                    sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 保险费
                    sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                    sb_f.append(format_f.format(new Date()));// 年月日时间
                    sb_f.append(OrderNumberConfig
                        .padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                    financialRecord.setCode(sb_f.toString());
                    financialRecord.setCompanyId(mainCompany.getId());
                    financialRecord.setCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setOrderCompanyId(mainCompany.getId());
                    financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setMemo(
                        "订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                            + order.getOrderNumber() + "</a>】信息费");
                    financialRecord.setMoney(orderCompany.getInfoFee());
                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                    financialRecord.setWho(driver.getRealname());
                    financialRecord.setOrderId(order.getId());
                    financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                    financialRecordMapper.insertRecord(financialRecord);

                    // 订单财务记录
                    orderFinishedInfo
                        .setInfoFee(orderFinishedInfo.getInfoFee().add(orderCompany.getInfoFee()));
                    // 订单财务记录
                }
                // 代驾险
                if (null != order.getDjxFee() && order.getDjxFee().doubleValue() != 0) {
                    driver.setVirtual(driver.getVirtual().subtract(order.getDjxFee()));
                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                    // 扣费记录
                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                    driverPaymentsRecord.setMoney(order.getDjxFee());
                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                    driverPaymentsRecord
                        .setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                    driverPaymentsRecord.setInfoFeeType(DriverPaymentsRecord.INFOFEE_TYPE_DJX);
                    driverPaymentsRecord.setDriverId(driver.getId());
                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                    driverPaymentsRecord.setOrderId(order.getId());
                    driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                    driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                    driverPaymentsRecord.setMemo("扣除公司所得代驾险" + order.getDjxFee() + "元。");
                    driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                    driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                    driverPaymentsRecord.setHappend(new Date());
                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                    // 财务记录（保险费）
                    Company mainCompany = companyMapper.selectMainCompany();
                    DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                    FinancialRecord financialRecord = new FinancialRecord();
                    StringBuilder sb_f = new StringBuilder();
                    sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 保险费
                    sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                    sb_f.append(format_f.format(new Date()));// 年月日时间
                    sb_f.append(OrderNumberConfig
                        .padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                    financialRecord.setCode(sb_f.toString());
                    financialRecord.setCompanyId(mainCompany.getId());
                    financialRecord.setCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setOrderCompanyId(mainCompany.getId());
                    financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setMemo(
                        "订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                            + order.getOrderNumber() + "</a>】代驾险");
                    financialRecord.setMoney(order.getDjxFee());
                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                    financialRecord.setWho(driver.getRealname());
                    financialRecord.setOrderId(order.getId());
                    financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                    financialRecordMapper.insertRecord(financialRecord);

                    // 保险记录
                    DjInsurance djInsurance = new DjInsurance();
                    djInsurance.setInsuranceType(DjInsurance.InsuranceType.djx);
                    djInsurance.setMoney(order.getDjxFee());
                    djInsurance.setOrderId(order.getId());
                    djInsurance.setOrderNo(order.getOrderNumber());
                    djInsuranceMapper.insertRecord(djInsurance);

                    DjxNoticeEvent djxNoticeEvent = new DjxNoticeEvent(driver, djInsurance);
                    applicationEventMulticaster.multicastEvent(djxNoticeEvent);

                    // 订单财务记录
                    orderFinishedInfo
                        .setDjxFee(orderFinishedInfo.getDjxFee().add(order.getDjxFee()));
                    // 订单财务记录
                }
                // 意外险
                if (null != order.getYwxFee() && order.getYwxFee().doubleValue() != 0) {
                    driver.setVirtual(driver.getVirtual().subtract(order.getYwxFee()));
                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                    // 扣费记录
                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                    driverPaymentsRecord.setMoney(order.getYwxFee());
                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                    driverPaymentsRecord
                        .setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                    driverPaymentsRecord.setInfoFeeType(DriverPaymentsRecord.INFOFEE_TYPE_YWX);
                    driverPaymentsRecord.setDriverId(driver.getId());
                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                    driverPaymentsRecord.setOrderId(order.getId());
                    driverPaymentsRecord.setOrderNumber(order.getOrderNumber());
                    driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                    driverPaymentsRecord.setMemo("扣除公司所得意外险" + order.getYwxFee() + "元。");
                    driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                    driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                    driverPaymentsRecord.setHappend(new Date());
                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                    // 财务记录（保险费）
                    Company mainCompany = companyMapper.selectMainCompany();
                    DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                    FinancialRecord financialRecord = new FinancialRecord();
                    StringBuilder sb_f = new StringBuilder();
                    sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 保险费
                    sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 服务人员
                    sb_f.append(format_f.format(new Date()));// 年月日时间
                    sb_f.append(OrderNumberConfig
                        .padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                    financialRecord.setCode(sb_f.toString());
                    financialRecord.setCompanyId(mainCompany.getId());
                    financialRecord.setCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setOrderCompanyId(mainCompany.getId());
                    financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setMemo(
                        "订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                            + order.getOrderNumber() + "</a>】意外险");
                    financialRecord.setMoney(order.getYwxFee());
                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                    financialRecord.setWho(driver.getRealname());
                    financialRecord.setOrderId(order.getId());
                    financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                    financialRecordMapper.insertRecord(financialRecord);

                    // 保险记录
                    DjInsurance djInsurance = new DjInsurance();
                    djInsurance.setInsuranceType(DjInsurance.InsuranceType.ywx);
                    djInsurance.setMoney(order.getYwxFee());
                    djInsurance.setOrderId(order.getId());
                    djInsurance.setOrderNo(order.getOrderNumber());
                    djInsuranceMapper.insertRecord(djInsurance);

                    YwxNoticeEvent ywxNoticeEvent = new YwxNoticeEvent(driver, djInsurance);
                    applicationEventMulticaster.multicastEvent(ywxNoticeEvent);

                    // 订单财务记录
                    orderFinishedInfo
                        .setYwxFee(orderFinishedInfo.getYwxFee().add(order.getYwxFee()));
                    // 订单财务记录
                }
            }

            if (adminComplete) {
                if (order.getBaoxiaoCash().doubleValue() > 0) {
                    // 财务记录（司机报销）
                    FinancialRecord financialRecord = new FinancialRecord();
                    StringBuilder sb = new StringBuilder();
                    sb.append(OrderNumberConfig.FINANCIAL_BAOXIAO);// 报销金额
                    sb.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象 司机
                    sb.append(format.format(new Date()));// 年月日时间
                    sb.append(OrderNumberConfig
                        .padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                    financialRecord.setCode(sb.toString());
                    financialRecord.setCompanyId(company.getId());
                    financialRecord.setCompanyName(company.getAbbreviation());
                    financialRecord.setOrderCompanyId(orderCompany.getId());
                    financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                    financialRecord.setMemo(
                        "订单号【<a target='_blank' href='/order/detail/" + order.getId() + "'>"
                            + order.getOrderNumber() + "</a>】,服务人员【" + driver.getRealname() + "】报销："
                            + order.getBaoxiaoMemo());
                    financialRecord.setMoney(order.getBaoxiaoCash().negate());
                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_WAIT);
                    financialRecord.setWho(driver.getRealname());
                    financialRecord.setOrderId(order.getId());
                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                    financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_BAOXIAO);
                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_DAIJIA);
                    financialRecordMapper.insertRecord(financialRecord);

                    order.setBaoxiao(true);
                }
            }

        } else {
            // 订单财务记录
            orderFinishedInfo.setDriverMoney(BigDecimal.ZERO);
            orderFinishedInfo
                .setCompanyMoney(order.getRealCash().subtract(orderFinishedInfo.getWxManagerMoney())
                    .subtract(order.getGuoluMoney()));
            // 订单财务记录
        }

        // 更新目的地
        if (!order.getHasToPlace()) {

        }

        // 更新订单
        orderMapper.updateByPrimaryKey(order);

        // 醉无忧 - 人保新加
        if (null != order.getOrderNoRenBao() && null != order.getCuponNoRenBao()) {
            zWYApi.syncOrderInfo(order.getOrderNoRenBao(), order.getCuponNoRenBao(),
                order.getOrderNumber(),
                String.valueOf(7), order.getClientPhone());
        }

        // 订单财务记录
        orderFinishedInfoMapper.insertRecord(orderFinishedInfo);
        // 订单财务记录

        // 结算成功保存首单免费客户信息
        FirstOrderPassenger firstOrderPassenger = new FirstOrderPassenger();
        firstOrderPassenger.setPassengerId(passenger.getId());
        firstOrderPassenger.setType(FirstOrderPassenger.FREE_ORDERTYPE_DAIJIA);
        firstOrderPassengerMapper.insertRecord(firstOrderPassenger);

        result.setSuccess(true);

        // } catch (Exception e) {
        // e.printStackTrace();
        // result.setSuccess(false);
        // result.setMessage("内部服务器错误");
        // }

        // lock.unlock();

        return result;
    }

    @Override
    public List<Order> daijialistExport(String orderNumber, String clientPhone, String driverPhone,
        String companyName,
        String createOrderName, String[] orderType, String[] status, boolean warm, Date start,
        Date end,
        Date startFinish, Date endFinish) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        String likeOrderNumber = null;
        String likeClientPhone = null;
        String likeDriverPhone = null;
        String likeCompanyName = null;
        String likeCreateOrderName = null;
        if (StringUtils.isNotBlank(orderNumber)) {
            likeOrderNumber = "%" + orderNumber + "%";
        }
        if (StringUtils.isNotBlank(clientPhone)) {
            likeClientPhone = "%" + clientPhone + "%";
        }
        if (StringUtils.isNotBlank(driverPhone)) {
            likeDriverPhone = "%" + driverPhone + "%";
        }
        if (principal.isCompanyType()) {
            if (StringUtils.isNotBlank(companyName)) {
                likeCompanyName = "%" + companyName + "%";
            }
        }
        if (StringUtils.isNotBlank(createOrderName)) {
            likeCreateOrderName = "%" + createOrderName + "%";
        }

        List<Integer> statusList = new ArrayList<Integer>();
        Boolean notpay = false;
        if (null != status && status.length > 0) {
            String statusStr = "";
            for (int i = 0; i < status.length; i++) {
                statusStr += status[i] + ",";
            }
            if (statusStr.contains("new")) {
                statusList.add(Order.ORDER_STATUS_NEW);
            }
            if (statusStr.contains("paidan")) {
                statusList.add(Order.ORDER_STATUS_YIPAIDAN);
            }
            if (statusStr.contains("busy")) {
                statusList.add(Order.ORDER_STATUS_BUSY);
            }
            if (statusStr.contains("notpay")) {
                notpay = true;
            }
            if (statusStr.contains("finish")) {
                statusList.add(Order.ORDER_STATUS_BAODAN);
            }
            if (statusStr.contains("cancel")) {
                statusList.add(Order.ORDER_STATUS_CANCELED);
            }
        }
        if (CollectionUtils.isEmpty(statusList)) {
            statusList = null;
        }

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -2);
        Date warmDate = calendar.getTime();
        Long companyId = null;
        if (!principal.isCompanyType()) {
            companyId = principal.getCompanyId();
        }

        List<Order> orderList = new ArrayList<Order>();
        Long total = orderMapper
            .countDaijiaList(null, companyId, likeOrderNumber, likeClientPhone, likeDriverPhone,
                likeCompanyName, likeCreateOrderName, orderType, statusList, notpay, warm, warmDate,
                start, end,
                startFinish, endFinish);

        Integer rows = 100;
        Integer currentRows = 0;
        Integer page = 0;

        while (currentRows < total) {
            List<Order> list = orderMapper
                .selectDaijiaList(null, companyId, likeOrderNumber, likeClientPhone,
                    likeDriverPhone, likeCompanyName, likeCreateOrderName, orderType, statusList,
                    notpay, warm,
                    warmDate, start, end, startFinish, endFinish, page * rows, rows);
            orderList.addAll(list);

            currentRows += rows;
            page++;
        }

        return orderList;
    }

    @Override
    public List<Order> findByGroup(Long orderGroupId) {
        return orderMapper.selectByGroup(orderGroupId);
    }

    @Override
    public long countNotPayByPassenger(Long passengerId) {
        return orderMapper.countNotPayByPassenger(passengerId);
    }

    @Override
    public long countNotFinishedByPassenger(Long passengerId) {
        return orderMapper.countNotFinishedByPassenger(passengerId);
    }

    @Override
    public long countTodayOrderByPassenger(Long passengerId) {
        return orderMapper.countTodayOrderByPassenger(passengerId);
    }

    @Override
    public List<Order> findReward(Long driverId, BigDecimal lowestMoney, Date start, Date end) {
        return orderMapper.findReward(driverId, lowestMoney, start, end);
    }

}
